9#include <analysis/modules/TrackIsoCalculator/TrackIsoCalculatorModule.h>
10#include <analysis/DecayDescriptor/DecayDescriptorParticle.h>
11#include <analysis/utility/DetectorSurface.h>
15#include <boost/algorithm/string.hpp>
26 R
"DOC(Calculate track isolation variables on the charged stable particles, or selected charged daughters, of the input ParticleList.)DOC");
31 "The name of the input charged stable particle list, e.g. ``mu+:all``, or a composite particle w/ charged stable daughters for which distances are to be calculated, e.g. ``D0 -> ^K- pi+``. Note that in the latter case we allow only one daughter to be selected in the decay string per module instance.");
34 "The name of the input ParticleList of reference tracks. Must be a charged stable particle as defined in Const::chargedStableSet.");
37 "The list of names of the detectors at whose (cylindrical) surface(s) we extrapolate each helix's polar and azimuthal angle. Allowed values: {CDC, TOP, ARICH, ECL, KLM}.",
38 std::vector<std::string>());
41 "If this option is set, the helix extrapolation for the target and reference particles will use the track fit result for the most probable mass hypothesis, namely, the one that gives the highest chi2Prob of the fit.",
45 "The name of the database payload object with the PID detector weights.",
46 std::string(
"PIDDetectorWeights"));
49 "If set to true, will not use the PID detector weights for the score definition.",
76 B2ERROR(
"More than one daughter is selected in the decay string " <<
m_decayString <<
".");
81 B2INFO(
"Calculating track-based isolation variables for the decay string: "
83 <<
" using the reference ParticleList: "
88 B2ERROR(
"Selected ParticleList in decay string:"
90 <<
" and/or reference ParticleList: "
92 <<
" is not that of a valid particle in Const::chargedStableSet!");
96 B2INFO(
"Will use track fit result for the most probable mass hypothesis in helix extrapolation.");
99 std::string detNamesConcat(
"");
104 boost::to_upper(detName);
106 detNamesConcat +=
"_" + detName;
112 auto iDetLayer = detName + std::to_string(iLayer);
116 distVarName +=
"__useHighestProbMassForExt";
146 std::unordered_map<unsigned int, const Particle*> targetParticles;
147 targetParticles.reserve(nMotherParticles);
149 for (
unsigned int iPart(0); iPart < nMotherParticles; ++iPart) {
159 auto iDetLayer = detName + std::to_string(iLayer);
168 targetParticles.insert({iDaughter->getMdstArrayIndex(), iDaughter});
174 targetParticles.insert({iParticle->getMdstArrayIndex(), iParticle});
181 const auto nParticlesTarget = targetParticles.size();
190 auto iDetLayer = detName + std::to_string(iLayer);
193 <<
"Detector surface: " << iDetLayer <<
"\n"
194 <<
"nMotherParticles: " << nMotherParticles <<
"\n"
195 <<
"nParticlesTarget: " << nParticlesTarget <<
"\n"
196 <<
"nParticlesReference: " << nParticlesReference);
198 double dummyDist(-1.0);
202 std::map<std::pair<unsigned int, unsigned int>,
double> particleMdstIdxPairsToDist;
205 for (
const auto& targetParticle : targetParticles) {
207 auto iMdstIdx = targetParticle.first;
208 auto iParticle = targetParticle.second;
210 for (
unsigned int jPart(0); jPart < nParticlesReference; ++jPart) {
213 auto jMdstIdx = jParticle->getMdstArrayIndex();
215 auto partMdstIdxPair = std::make_pair(iMdstIdx, jMdstIdx);
218 if (iMdstIdx == jMdstIdx) {
219 particleMdstIdxPairsToDist[partMdstIdxPair] = dummyDist;
229 if (particleMdstIdxPairsToDist.count({jMdstIdx, iMdstIdx})) {
230 particleMdstIdxPairsToDist[partMdstIdxPair] = particleMdstIdxPairsToDist[ {jMdstIdx, iMdstIdx}];
235 particleMdstIdxPairsToDist[partMdstIdxPair] = this->
getDistAtDetSurface(iParticle, jParticle, iDetLayer);
241 for (
const auto& targetParticle : targetParticles) {
243 auto iMdstIdx = targetParticle.first;
244 auto iParticle = targetParticle.second;
247 std::vector<std::pair<double, unsigned int>> iDistancesAndRefMdstIdxs;
248 for (
const auto& [mdstIdxs, dist] : particleMdstIdxPairsToDist) {
249 if (mdstIdxs.first == iMdstIdx) {
250 if (!std::isnan(dist) && dist >= 0) {
251 iDistancesAndRefMdstIdxs.push_back(std::make_pair(dist, mdstIdxs.second));
256 if (!iDistancesAndRefMdstIdxs.size()) {
257 B2DEBUG(12,
"The container of distances is empty. Perhaps the target and reference lists contain the same exact particles?");
261 const auto minDist = *std::min_element(std::begin(iDistancesAndRefMdstIdxs), std::end(iDistancesAndRefMdstIdxs),
262 [](
const auto & l,
const auto & r) {
return l.first < r.first;});
267 <<
"Particle w/ mdstIndex[" << iMdstIdx <<
"] (PDG = "
268 << iParticle->getPDGCode() <<
"). Closest charged particle w/ mdstIndex["
270 <<
"] (PDG = " << jParticle->getPDGCode()
271 <<
") at " << iDetLayer
272 <<
" surface is found at D = " << minDist.first
274 <<
"Storing extraInfo variables:\n"
291 for (
const auto& targetParticle : targetParticles) {
293 auto iMdstIdx = targetParticle.first;
294 auto iParticle = targetParticle.second;
297 double isoScore(0.0);
298 double isoScoreAsWeightedAvg(0.0);
299 double sumWeights(0.0);
301 B2DEBUG(11,
"Particle w/ mdstIndex[" << iMdstIdx <<
"] (PDG = " << iParticle->getPDGCode() <<
").");
310 isoScore += weightedSumNonIsoLayers;
311 isoScoreAsWeightedAvg += weightedSumInvDists;
312 sumWeights += detWeight;
319 isoScore = (isoScore - minScore) / (maxScore - minScore);
321 isoScoreAsWeightedAvg /= sumWeights;
325 isoScoreAsWeightedAvg = 1. - ((std::min(isoScoreAsWeightedAvg, 1e2) - minScore) / (1e2 - minScore));
328 <<
"Isolation score: " << isoScore
330 <<
"Isolation score (as weighted avg): " << isoScoreAsWeightedAvg
332 <<
"Storing extraInfo variable:\n"
355 auto p = iParticle->
getP();
359 auto detWeight = (*
m_DBWeights.get())->getWeight(hypo, det, p, theta);
363 detWeight = (detWeight < 0 || std::isnan(detWeight)) ? detWeight : 0.0;
371 const float detWeight)
const
379 auto iDetLayer = detName + std::to_string(iLayer);
392 B2DEBUG(12,
"\nNo close-enough neighbours to this particle in the " << detName <<
" were found.");
396 B2FATAL(
"\nTotal layers in " << detName <<
": N=" << nLayers
398 <<
"Layers w/ a close-enough particle: n=" << n
400 <<
"n > N ?? Abort...");
403 return 1. - (-detWeight * (n / nLayers));
409 const float detWeight)
const
414 double sumInvDists(0.);
417 auto iDetLayer = detName + std::to_string(iLayer);
422 sumInvDists += threshDist / iParticle->
getExtraInfo(distVar);
427 return detWeight * sumInvDists;
434 const std::string& detLayerName)
const
447 std::string nameExtTheta =
"helixExtTheta(" + std::to_string(rho) +
"," + std::to_string(zfwd) +
"," + std::to_string(zbwd) +
")";
449 nameExtTheta.replace(nameExtTheta.size() - 1, 1,
", 1)");
454 std::string nameExtPhi =
"helixExtPhi(" + std::to_string(rho) +
"," + std::to_string(zfwd) +
"," + std::to_string(zbwd) +
")";
456 nameExtPhi.replace(nameExtPhi.size() - 1, 1,
", 1)");
461 const auto iExtInBarrel = (iExtTheta >= th_fwd_brl && iExtTheta < th_bwd_brl);
462 const auto jExtInBarrel = (jExtTheta >= th_fwd_brl && jExtTheta < th_bwd_brl);
464 const auto iExtInFWDEndcap = (iExtTheta >= th_fwd && iExtTheta < th_fwd_brl);
465 const auto jExtInFWDEndcap = (jExtTheta >= th_fwd && jExtTheta < th_fwd_brl);
467 const auto iExtInBWDEndcap = (iExtTheta >= th_bwd_brl && iExtTheta < th_bwd);
468 const auto jExtInBWDEndcap = (jExtTheta >= th_bwd_brl && jExtTheta < th_bwd);
470 if (boost::contains(detLayerName,
"CDC") || boost::contains(detLayerName,
"TOP")) {
473 if (!iExtInBarrel || !jExtInBarrel) {
474 return std::numeric_limits<double>::quiet_NaN();
481 auto diffPhi = jExtPhi - iExtPhi;
482 if (std::abs(diffPhi) > M_PI) {
483 diffPhi = (diffPhi > M_PI) ? diffPhi - 2 * M_PI : 2 * M_PI + diffPhi;
486 return 2.0 * rho * sin(std::abs(diffPhi) / 2.0);
490 if (boost::contains(detLayerName,
"ARICH")) {
492 if (!iExtInFWDEndcap || !jExtInFWDEndcap) {
493 return std::numeric_limits<double>::quiet_NaN();
496 if (boost::contains(detLayerName,
"ECL") || boost::contains(detLayerName,
"KLM")) {
501 !(iExtInBarrel && jExtInBarrel) &&
502 !(iExtInFWDEndcap && jExtInFWDEndcap) &&
503 !(iExtInBWDEndcap && jExtInBWDEndcap)
505 return std::numeric_limits<double>::quiet_NaN();
519 const auto iExtR = (iExtTheta >= th_fwd_brl && iExtTheta < th_bwd_brl) ? rho / sin(iExtTheta) : ((iExtTheta >= th_fwd
520 && iExtTheta < th_fwd_brl) ? zfwd / cos(iExtTheta) : zbwd / cos(iExtTheta));
521 const auto jExtR = (jExtTheta >= th_fwd_brl && jExtTheta < th_bwd_brl) ? rho / sin(jExtTheta) : ((jExtTheta >= th_fwd
522 && jExtTheta < th_fwd_brl) ? zfwd / cos(jExtTheta) : zbwd / cos(jExtTheta));
524 return sqrt((iExtR * iExtR) + (jExtR * jExtR) - 2 * iExtR * jExtR * (sin(iExtTheta) * sin(jExtTheta) * cos(iExtPhi - jExtPhi)
525 + cos(iExtTheta) * cos(jExtTheta)));
529 return std::numeric_limits<double>::quiet_NaN();
536 bool checkPList =
false;
550 bool checkPListReference =
false;
555 return (checkPList and checkPListReference);
Provides a type-safe way to pass members of the chargedStableSet set.
const ParticleType & find(int pdg) const
Returns particle in set with given PDG code, or invalidParticle if not found.
static const ParticleSet chargedStableSet
set of charged stable particles
static const ParticleType invalidParticle
Invalid particle, used internally.
Represents a particle in the DecayDescriptor.
int getPDGCode() const
Return PDG code.
std::string getFullName() const
returns the full name of the particle full_name = name:label
The DecayDescriptor stores information about a decay tree or parts of a decay tree.
bool init(const std::string &str)
Initialise the DecayDescriptor from given string.
std::vector< int > getSelectionPDGCodes()
Return list of PDG codes of selected particles.
std::vector< std::string > getSelectionNames()
Return list of human readable names of selected particles.
std::vector< const Particle * > getSelectionParticles(const Particle *particle)
Get a vector of pointers with selected daughters in the decay tree.
const DecayDescriptorParticle * getMother() const
return mother.
void setDescription(const std::string &description)
Sets the description of the module.
Class to store reconstructed particles.
bool hasExtraInfo(const std::string &name) const
Return whether the extra info with the given name is set.
int getPDGCode(void) const
Returns PDG code.
ROOT::Math::XYZVector getMomentum() const
Returns momentum vector.
double getP() const
Returns momentum magnitude (same as getMomentumMagnitude but with shorter name)
double getExtraInfo(const std::string &name) const
Return given value if set.
StoreObjPtr< EventMetaData > m_event_metadata
The event information.
std::unique_ptr< DBObjPtr< PIDDetectorWeights > > m_DBWeights
Interface to get the database payload with the PID detector weights.
~TrackIsoCalculatorModule() override
Destructor, use this to clean up anything you created in the constructor.
void initialize() override
Use this to initialize resources or memory your module needs.
double getDistAtDetSurface(const Particle *iParticle, const Particle *jParticle, const std::string &detLayerName) const
Calculate the distance between the points where the two input extrapolated track helices cross the gi...
void event() override
Called once for each event.
std::unordered_map< std::string, std::string > m_detLayerToDistVariable
Map that associates to each detector layer (e.g., 'CDC6') the name of the variable representing the d...
std::string m_decayString
The name of the input charged stable particle list, or composite particle w/ charged stable daughters...
StoreObjPtr< ParticleList > m_pListTarget
The input ParticleList object for which distances are to be calculated.
std::string m_isoScoreVariable
The name of the variable representing the track isolation score.
double getWeightedSumInvDists(const Particle *iParticle, const std::string &detName, const float detWeight) const
Get the sum of the inverse (scaled) minimum distances over the given detector layers,...
StoreArray< Particle > m_particles
StoreArray of Particles.
std::string m_payloadName
The name of the database payload object with the MVA weights.
std::vector< std::string > m_detNames
The list of names of the detectors at whose inner (cylindrical) surface we extrapolate each track's p...
Const::EDetector getDetEnum(const std::string &detName) const
Get the enum type for this detector name.
std::string m_pListReferenceName
The name of the input ParticleList of reference tracks.
std::unordered_map< std::string, std::string > m_detLayerToRefPartIdxVariable
Map that associates to each detector layer (e.g, 'CDC6') the name of the variable representing the md...
double getDistThreshold(Const::EDetector det, int layer) const
Get the threshold value per detector layer for the distance to closest ext.
bool onlySelectedStdChargedInDecay()
Check whether input particle list and reference list are of a valid charged stable particle.
double getDetectorWeight(const Particle *iParticle, const std::string &detName) const
Get the PID weight, , for this particle and detector reading it from the payload, if selected.
bool m_excludePIDDetWeights
Exclude the PID detector weights for the isolation score definition.
DecayDescriptor m_decaydescriptor
< Decay descriptor of decays to look for.
TrackIsoCalculatorModule()
Constructor: Sets the description, the properties and the parameters of the module.
double getWeightedSumNonIsoLayers(const Particle *iParticle, const std::string &detName, const float detWeight) const
Get the sum of layers with a close-by track, divided by the total number of layers,...
unsigned short m_nSelectedDaughters
The number of selected daughters in the decay string.
StoreObjPtr< ParticleList > m_pListReference
The input ParticleList object of reference tracks.
std::string m_isoScoreVariableAsWeightedAvg
The name of the variable representing the track isolation score.
bool m_useHighestProbMassForExt
If this option is set, the helix extrapolation for the target and reference particles will use the tr...
static Manager & Instance()
get singleton instance.
void addParam(const std::string &name, T ¶mVariable, const std::string &description, const T &defaultValue)
Adds a new parameter to the module.
#define REG_MODULE(moduleName)
Register the given module (without 'Module' suffix) with the framework.
Abstract base class for different kinds of events.
static const std::unordered_map< std::string, DetSurfCylBoundaries > detLayerToSurfBoundaries
Map that associates to each detector layer its valid cylindrical surface's boundaries.
static const std::unordered_map< std::string, std::vector< int > > detToLayers
Map that associates to each detector its list of valid layers.