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

Move FairModule::fAllSensitiveVolumes to FairRunSim #1500

Open
wants to merge 2 commits into
base: dev
Choose a base branch
from

Conversation

ChristianTackeGSI
Copy link
Member

@ChristianTackeGSI ChristianTackeGSI commented Mar 8, 2024

Instead of using a thread local, let's use something that is tied to the "simulaion session" (as noted in some places).

FairRunSim has all the Modules anyway, so let it also have the list of sensitive Volumes.

OR should we move it to FairMCApplcation instead?

waiting for:


Checklist:

Copy link

coderabbitai bot commented Mar 8, 2024

Walkthrough

Walkthrough

The updates refine how the Fair simulation framework manages sensitive volumes by centralizing relevant functionality within the FairRunSim class. This involves using UpdateSensitiveVolumesForModule in the FairDetector class and modifying iterations over sensitive volumes to utilize this new method. Additionally, the RegisterSensitiveVolume function now requires a FairRunSim instance, streamlining the association between modules and MC IDs.

Changes

Files Change Summary
fairroot/base/sim/FairDetector.cxx FairDetector::Initialize() now uses GetRunSim().UpdateSensitiveVolumesForModule(*this) to update MC IDs for sensitive volumes.
fairroot/base/sim/FairMCApplication.cxx Loop iteration over sensitive volumes updated to use fRun->RangeAllSensitiveVolumes() instead of FairModule::fAllSensitiveVolumes.
fairroot/base/sim/FairModule.cxx, fairroot/base/sim/FairModule.h Removed thread-local vector fAllSensitiveVolumes, updated RegisterSensitiveVolume to call fRunSim->RegisterSensitiveVolume(vol), and added assertions for fRunSim.
fairroot/base/steer/FairRunSim.cxx, fairroot/base/steer/FairRunSim.h Introduced UpdateSensitiveVolumesForModule, RegisterSensitiveVolume, and RangeAllSensitiveVolumes methods, and added fAllSensitiveVolumes as a member variable.

Sequence Diagram(s)

sequenceDiagram
  participant FairDetector
  participant FairRunSim
  participant FairMCApplication

  FairDetector->>FairRunSim: Initialize()
  FairRunSim->>FairDetector: UpdateSensitiveVolumesForModule(*this)

  FairMCApplication->>FairRunSim: InitGeometry()
  FairRunSim->>FairMCApplication: Access RangeAllSensitiveVolumes()
Loading

This diagram illustrates the interaction between FairDetector, FairRunSim, and FairMCApplication in initializing and updating sensitive volumes.

Possibly related PRs


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 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 or @coderabbitai title 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.

fairroot/base/sim/FairMCApplication.cxx Outdated Show resolved Hide resolved
fairroot/base/sim/FairModule.cxx Outdated Show resolved Hide resolved
fairroot/base/sim/FairModule.cxx Outdated Show resolved Hide resolved
karabowi
karabowi previously approved these changes Jun 6, 2024
@karabowi
Copy link
Collaborator

karabowi commented Jun 6, 2024

@ChristianTackeGSI, can you add an entry in the changelog? For some users that change may be worth mentioning.
I have tested the PR with PandaRoot.

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

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

fairroot/base/sim/FairMCApplication.cxx Outdated Show resolved Hide resolved
fairroot/base/sim/FairModule.cxx Outdated Show resolved Hide resolved
@ChristianTackeGSI
Copy link
Member Author

@ChristianTackeGSI, can you add an entry in the changelog? For some users that change may be worth mentioning. I have tested the PR with PandaRoot.

fAllSenstiveVolumes was introduced during a rename for 19.0. So the rename was a breaking change. You correctly identified, that we did not document it properly. So let's document it now: #1555

After the docs have been reviewed and merged (and backported to 19.0), I will rebase this one.

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.

Caution

Inline review comments failed to post

Actionable comments posted: 1

Outside diff range, codebase verification and nitpick comments (1)
fairroot/base/steer/FairRunSim.h (1)

228-240: LGTM, but consider adding documentation comments.

The new member functions are necessary for managing sensitive volumes in the simulation framework. However, it would be helpful to add documentation comments to describe their purpose and usage in more detail.

Consider adding documentation comments for the new member functions, for example:

/**
 * \brief Register a sensitive volume
 * 
 * Adds the given sensitive volume to the list of all sensitive volumes.
 * 
 * \param vol The sensitive volume to register
 */
void RegisterSensitiveVolume(FairVolume& vol) { fAllSensitiveVolumes.push_back(&vol); }

/**
 * \brief Get a range of all sensitive volumes
 * 
 * Returns a constant reference to the vector of all sensitive volumes.
 * This allows iterating over the sensitive volumes without modifying the list.
 * 
 * \return Constant reference to the vector of all sensitive volumes
 */
auto const& RangeAllSensitiveVolumes() const { return fAllSensitiveVolumes; }

/**
 * \brief Update sensitive volumes for a module
 * 
 * Internal helper function for FairDetector.
 * Updates the list of sensitive volumes for the given module.
 * 
 * \param mod The module to update sensitive volumes for
 */
void UpdateSensitiveVolumesForModule(FairModule& mod);
Comments failed to post (1)
fairroot/base/steer/FairRunSim.cxx (1)

436-455: Improve the UpdateSensitiveVolumesForModule method with null check, range-based for loop, and better variable naming.

The new UpdateSensitiveVolumesForModule method is logically sound and follows good coding practices. However, consider the following improvements:

  1. Add a null check for TVirtualMC::GetMC() to prevent potential runtime errors.
  2. Use a range-based for loop and structured bindings to simplify the code and improve readability.
  3. Rename aVol to a more descriptive name like sensitiveVolume.

Apply this diff to implement the suggested improvements:

void FairRunSim::UpdateSensitiveVolumesForModule(FairModule& mod)
{
    TString copysign = "#";
-   for (auto aVol : fAllSensitiveVolumes) {
-       if (aVol->getModId() != mod.GetModId()) {
+   for (const auto& [sensitiveVolume, _] : fAllSensitiveVolumes) {
+       if (sensitiveVolume->getModId() != mod.GetModId()) {
            continue;
        }
-       TString cutName{aVol->GetName()};
+       TString cutName{sensitiveVolume->GetName()};
        Ssiz_t pos = cutName.Index(copysign, 1);
        if (pos > 1) {
            cutName.Resize(pos);
        }
+       if (TVirtualMC::GetMC() == nullptr) {
+           LOG(error) << "TVirtualMC::GetMC() returned nullptr. Unable to update sensitive volume: " << cutName;
+           continue;
+       }
        Int_t mcid = TVirtualMC::GetMC()->VolId(cutName.Data());
-       aVol->setMCid(mcid);
-       FairGeoNode* node = aVol->getGeoNode();
+       sensitiveVolume->setMCid(mcid);
+       FairGeoNode* node = sensitiveVolume->getGeoNode();
        if (node) {
            node->setMCid(mcid);
        }
    }
}
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.

void FairRunSim::UpdateSensitiveVolumesForModule(FairModule& mod)
{
    TString copysign = "#";
    for (const auto& [sensitiveVolume, _] : fAllSensitiveVolumes) {
        if (sensitiveVolume->getModId() != mod.GetModId()) {
            continue;
        }
        TString cutName{sensitiveVolume->GetName()};
        Ssiz_t pos = cutName.Index(copysign, 1);
        if (pos > 1) {
            cutName.Resize(pos);
        }
        if (TVirtualMC::GetMC() == nullptr) {
            LOG(error) << "TVirtualMC::GetMC() returned nullptr. Unable to update sensitive volume: " << cutName;
            continue;
        }
        Int_t mcid = TVirtualMC::GetMC()->VolId(cutName.Data());
        sensitiveVolume->setMCid(mcid);
        FairGeoNode* node = sensitiveVolume->getGeoNode();
        if (node) {
            node->setMCid(mcid);
        }
    }
}

@ChristianTackeGSI ChristianTackeGSI marked this pull request as ready for review September 4, 2024 19:59
@ChristianTackeGSI
Copy link
Member Author

@ChristianTackeGSI, can you add an entry in the changelog? For some users that change may be worth mentioning. I have tested the PR with PandaRoot.

fAllSenstiveVolumes was introduced during a rename for 19.0. So the rename was a breaking change. You correctly identified, that we did not document it properly. So let's document it now: #1555

After the docs have been reviewed and merged (and backported to 19.0), I will rebase this one.

Instead of using a thread local, let's use something that
is tied to the "simulaion session" (as noted in some places).

FairRunSim has all the Modules anyway, so let it also have
the list of sensitive Volumes.
A part of FairDetector::Initialize updates the sensitive
volumes related to that Detector(Module). Instead of
handling this inline, move the code to a new member
function on FairRunSim.
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 and nitpick comments (1)
fairroot/base/sim/FairMCApplication.cxx (1)

Line range hint 883-908: Consider adding checks or logging for empty sensitive volumes list.

Based on the insights from the past comments, it would be beneficial to handle scenarios where fRun->RangeAllSensitiveVolumes() might return an empty list. Consider adding checks or logging statements to alert about such cases and prevent potential issues in the simulation.

For example, you could add a check like this:

+if (fRun->RangeAllSensitiveVolumes().empty()) {
+  LOG(warn) << "No sensitive volumes found in fRun->RangeAllSensitiveVolumes()";
+}
 for (auto fv : fRun->RangeAllSensitiveVolumes()) {
   // ...
 }
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between fcddccb and a0a41df.

Files selected for processing (6)
  • fairroot/base/sim/FairDetector.cxx (2 hunks)
  • fairroot/base/sim/FairMCApplication.cxx (1 hunks)
  • fairroot/base/sim/FairModule.cxx (2 hunks)
  • fairroot/base/sim/FairModule.h (2 hunks)
  • fairroot/base/steer/FairRunSim.cxx (2 hunks)
  • fairroot/base/steer/FairRunSim.h (3 hunks)
Additional comments not posted (13)
fairroot/base/sim/FairDetector.cxx (2)

17-17: LGTM!

The addition of the FairRunSim.h include statement is necessary to use the UpdateSensitiveVolumesForModule method from the FairRunSim class, as part of the refactoring to move sensitive volume management to FairRunSim.


97-97: Verify the UpdateSensitiveVolumesForModule implementation.

The refactoring to replace the sensitive volume update loop with a call to GetRunSim().UpdateSensitiveVolumesForModule(*this) aligns with the PR objective and simplifies the Initialize method.

However, it's crucial to ensure that the UpdateSensitiveVolumesForModule method in FairRunSim correctly updates the Monte Carlo IDs for all sensitive volumes associated with the module.

Please provide the implementation of UpdateSensitiveVolumesForModule or point to the relevant code changes for review.

Alternatively, consider adding unit tests to verify the behavior of UpdateSensitiveVolumesForModule and confirm that it achieves the same result as the original loop logic.

fairroot/base/sim/FairModule.h (2)

28-28: LGTM!

Including the <cassert> header is a good practice for using runtime assertions to catch and handle unexpected conditions during development and testing.


194-202: LGTM!

The addition of the GetRunSim() method is a useful feature that allows retrieving the associated FairRunSim object for the module. The assertion assert(fRunSim) is a good safety check to ensure that fRunSim is properly set before dereferencing it, helping catch potential bugs early.

fairroot/base/steer/FairRunSim.h (4)

24-24: LGTM!

Including the <vector> header is necessary for using std::vector in the code. This is a valid addition.


228-235: LGTM!

The addition of the RegisterSensitiveVolume and RangeAllSensitiveVolumes functions to the FairRunSim class is a good way to manage sensitive volumes. The implementation looks correct and follows best practices.


237-240: Request for more information

The purpose and implementation details of the UpdateSensitiveVolumesForModule function are not clear from this header file. Could you please provide more context or the function definition to help understand its behavior and assess its correctness?


258-261: LGTM!

The addition of the fAllSensitiveVolumes member variable to store a list of all sensitive volumes in a simulation session is appropriate. Using a std::vector to hold the pointers is a suitable choice. The comment clearly indicates its purpose and internal usage.

fairroot/base/steer/FairRunSim.cxx (2)

439-454: LGTM!

The function correctly updates the Monte Carlo IDs of sensitive volumes associated with a given module by iterating through fAllSensitiveVolumes, matching the module ID, processing the volume name, and setting the mcid for both the sensitive volume and its associated geometry node.


438-447: Clarify the purpose and implications of removing the suffix after the # character in the volume name.

The code processes the volume name to remove any suffix after a specific character (#). It would be helpful to provide more context on why this is necessary and how it affects the volume naming convention throughout the codebase.

Verification successful

Clarification on the purpose and implications of removing the suffix after the # character in the volume name

The code in FairRunSim.cxx is processing sensitive volume names to remove suffixes marked by the "#" character. This is done in the UpdateSensitiveVolumesForModule method, which is likely called during the simulation setup or update phase. Here's a breakdown of the process and its implications:

  1. Purpose: The code is designed to standardize volume names by removing any suffixes that come after a "#" character. This could be used to handle variations or copies of the same basic volume type.

  2. Process: For each sensitive volume associated with the current module, the code:

    • Looks for the first "#" character in the volume name.
    • If found (and not at the start of the name), it truncates the name at that point.
  3. Implications:

    • This allows for a naming convention where base volume names can be extended with suffixes for specific instances or copies, while still being recognized by their base name in the simulation.
    • It ensures that when querying volume IDs from the Monte Carlo simulation, the base name is used, potentially mapping multiple suffixed versions to the same core volume definition.
  4. Usage in simulation: After processing the name, it's used to retrieve the volume ID from the Monte Carlo simulation. This suggests that the simulation setup should use the base names (without suffixes) when defining volumes.

  5. Consistency: This approach requires consistent use of the "#" convention across the detector setup and simulation configuration to work correctly.

This naming convention and processing allow for more flexible volume naming in the detector description while maintaining a simpler structure in the underlying simulation. However, it also means that care must be taken in naming volumes and understanding how these names will be interpreted during the simulation process.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of the `#` character in sensitive volume names.

# Test: Search for sensitive volume name patterns containing `#`. Expect: Relevant occurrences demonstrating the naming convention.
rg --type cpp $'->GetName\\(\\).*#'

Length of output: 439


Script:

#!/bin/bash
# Description: Verify the usage of the `#` character in volume names.

# Search for method calls returning names containing the `#` character
echo "Searching for volume names with '#':"
rg --type cpp "->.*Name\(\).*#"

# Search for method calls returning names without the `#` character
echo "Searching for volume names without '#':"
rg --type cpp "->.*Name\(\)[^#]*$"

Length of output: 1064


Script:

#!/bin/bash
# Description: Verify the usage of the `#` character in potential volume names.

# Search for potential volume names containing the `#` character
echo "Searching for potential volume names with '#':"
rg -i --type cpp "(volume|vol|detector).*#"

# Search for potential volume names without the `#` character
echo "Searching for potential volume names without '#':"
rg -i --type cpp "(volume|vol|detector)[^#]*$"

# Search for any occurrences of `#` in strings
echo "Searching for any '#' in strings:"
rg -i --type cpp '"[^"]*#[^"]*"'

Length of output: 376723


Script:

#!/bin/bash
# Description: Search for volume name processing in FairRunSim.cxx

# Look for the specific code snippet and surrounding context
echo "Searching for volume name processing in FairRunSim.cxx:"
rg -A 10 -B 5 "TString copysign = \"#\";" fairroot/base/steer/FairRunSim.cxx

# Search for any other occurrences of volume name processing
echo "\nSearching for other volume name processing:"
rg -i "volume.*name" fairroot/base/steer/FairRunSim.cxx

Length of output: 864

fairroot/base/sim/FairModule.cxx (2)

217-221: LGTM!

The changes align with the PR objective of moving the management of sensitive volumes to FairRunSim. The assertion adds a good safety check. The logic is correct and the implementation is clean.


Line range hint 279-289: LGTM!

The changes introduce a null check for the volume being added, which is a good safety measure. The logic of adding the volume to vList and then registering it as a sensitive volume is correct. The implementation is clean.

fairroot/base/sim/FairMCApplication.cxx (1)

Line range hint 883-908: Verify the sensitive volumes returned by fRun->RangeAllSensitiveVolumes().

The changes align with the PR's objective of centralizing sensitive volume management. However, it's crucial to ensure that fRun->RangeAllSensitiveVolumes() returns a properly initialized and populated list of sensitive volumes. Incorrect or missing volumes could lead to issues in the simulation.

Run the following script to verify the sensitive volumes:

Verification successful

To complete our verification, we need to gather more information about how sensitive volumes are managed in FairRunSim. Let's run additional scripts to investigate this further.


To complete our verification, we need to investigate how fAllSensitiveVolumes is declared and populated in FairRunSim. Let's run additional scripts to gather this information.


To complete our verification, we need to investigate how RegisterSensitiveVolume is called and check the FairRunSim constructor. Let's run one final set of scripts to gather this information.


Verification successful: Sensitive volumes are properly managed

The investigation confirms that fAllSensitiveVolumes in FairRunSim is correctly declared, initialized, and populated. The RegisterSensitiveVolume method in FairRunSim is called by FairModule instances to add sensitive volumes. This mechanism ensures that fRun->RangeAllSensitiveVolumes() returns the expected list of sensitive volumes in FairMCApplication.

Key findings:

  1. fAllSensitiveVolumes is declared as a std::vector<FairVolume*> in FairRunSim.
  2. It's populated through the RegisterSensitiveVolume method, called by FairModule instances.
  3. The constructor doesn't explicitly initialize it, which is correct for a std::vector.
  4. Usage in FairRunSim and FairMCApplication is consistent with this implementation.

The changes align with the PR's objective of centralizing sensitive volume management, and the verification process has not revealed any issues.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the sensitive volumes returned by `fRun->RangeAllSensitiveVolumes()`.

# Test: Search for the usage of `RangeAllSensitiveVolumes()`. Expect: Calls from `FairRunSim` or related classes.
rg --type cpp -A 5 $'RangeAllSensitiveVolumes\(\)'

# Test: Search for the initialization of sensitive volumes in `FairRunSim`. Expect: Code that populates the sensitive volumes list.
ast-grep --lang cpp --pattern $'class FairRunSim {
  $$$
  void InitSensitiveVolumes($$$) {
    $$$
  }
  $$$
}'

Length of output: 1332


Script:

#!/bin/bash
# Description: Further investigate sensitive volume management in FairRunSim

# Search for the implementation of UpdateSensitiveVolumesForModule
rg --type cpp -A 10 "void FairRunSim::UpdateSensitiveVolumesForModule"

# Look for methods in FairRunSim that modify fAllSensitiveVolumes
ast-grep --lang cpp --pattern 'class FairRunSim {
  $$$
  void $METHOD_NAME($$$) {
    $$$
    fAllSensitiveVolumes$$$
    $$$
  }
  $$$
}'

Length of output: 1314


Script:

#!/bin/bash
# Description: Investigate declaration and population of fAllSensitiveVolumes in FairRunSim

# Search for the declaration of fAllSensitiveVolumes
rg --type cpp "fAllSensitiveVolumes" fairroot/base/steer/FairRunSim.h

# Look for direct assignments to fAllSensitiveVolumes
rg --type cpp "fAllSensitiveVolumes\s*=" fairroot/base/steer/FairRunSim.cxx

# Search for methods in FairRunSim that might indirectly populate fAllSensitiveVolumes
rg --type cpp -A 10 "void FairRunSim::(Init|AddModule|SetModule)" fairroot/base/steer/FairRunSim.cxx

Length of output: 1048


Script:

#!/bin/bash
# Description: Investigate calls to RegisterSensitiveVolume and FairRunSim constructor

# Search for calls to RegisterSensitiveVolume
rg --type cpp "RegisterSensitiveVolume"

# Look for the FairRunSim constructor
rg --type cpp -A 10 "FairRunSim::FairRunSim" fairroot/base/steer/FairRunSim.cxx

# Search for any initialization of fAllSensitiveVolumes in FairRunSim.cxx
rg --type cpp "fAllSensitiveVolumes" fairroot/base/steer/FairRunSim.cxx

Length of output: 1075

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.

2 participants