Belle II Software  release-08-01-10
SecMapTrainer.h
1 /**************************************************************************
2  * basf2 (Belle II Analysis Software Framework) *
3  * Author: The Belle II Collaboration *
4  * *
5  * See git log for contributors and copyright holders. *
6  * This file is licensed under LGPL-3.0, see LICENSE.md. *
7  **************************************************************************/
8 
9 #pragma once
10 
11 #include <tracking/spacePointCreation/SpacePointTrackCand.h>
12 
13 #include <tracking/trackFindingVXD/sectorMapTools/SecMapTrainerHit.h>
14 #include <tracking/trackFindingVXD/sectorMapTools/SecMapTrainerTC.h>
15 #include <tracking/dataobjects/SectorMapConfig.h>
16 #include <tracking/trackFindingVXD/environment/VXDTFFilters.h>
17 
18 #include <tracking/trackFindingVXD/sectorMapTools/FilterMill.h>
19 #include <tracking/trackFindingVXD/sectorMapTools/RawSecMapRootInterface.h>
20 //#include <tracking/trackFindingVXD/sectorMapTools/SectorTools.h>
21 #include <tracking/trackFindingVXD/filterMap/map/FiltersContainer.h>
22 #include <tracking/trackFindingVXD/filterMap/filterFramework/SelectionVariableNamesToFunctions.h>
23 #include <framework/geometry/B2Vector3.h>
24 
25 #include <tracking/dataobjects/FullSecID.h>
26 #include <vxd/dataobjects/VxdID.h>
27 
28 #include <string>
29 #include <vector>
30 #include <utility> // std::pair, std::move
31 #include <limits> // std::numeric_limits
32 
33 
34 namespace Belle2 {
42  template <class FilterFactoryType>
43  class SecMapTrainer {
44  protected:
46  const std::string m_nameSetup;
47 
51 
55 
57  FilterFactoryType m_factory;
58 
61 
62 
65 
66 
68  std::vector<SecMapTrainerTC> m_tcs;
69 
70 
72  unsigned m_expNo;
73 
74 
76  unsigned m_runNo;
77 
78 
80  unsigned m_evtNo;
81 
82 
83 
87  bool acceptHit(const SpacePoint& hit)
88  {
89  // rejects if layerID is not acceptable for this secMap-training.
90  auto layerID = hit.getVxdID().getLayerNumber();
91  bool found = false;
92  std::string ids = "";
93  for (auto allowedLayer : m_config.allowedLayers) {
94  ids += std::to_string(allowedLayer) + " ";
95  if (allowedLayer == layerID) found = true;
96  }
97  B2DEBUG(20, "SecMapTrainer::acceptHit: the TC has layerID: " << layerID << " and allowd layers: " << ids << " and was " <<
98  (found ? "accepted" : "rejected"));
99 
100  return found;
101  }
102 
103 
104 
107  {
108  unsigned nValues = 0;
109  B2DEBUG(20, "SecMapTrainer::process2HitCombinations: nHits/trackID/pdg: " << aTC.size() << "/" << aTC.getTrackID() << "/" <<
110  aTC.getPDG());
111  if (aTC.size() < 2) { return nValues; }
112 
113  // the iterators mark the hits to be used:
116 
117  // loop over all 2-hit-combis, collect data for each filterType and store it in root-tree:
118  std::vector<std::pair<std::string, double> > collectedResults;
119  for (; innerIt != aTC.innerEnd();) {
120  B2DEBUG(20, "SecMapTrainer::process2HitCombinations: outerHit-/innerHitSecID: " << outerIt->getSectorIDString() <<
121  "/" << innerIt->getSectorIDString());
122 
123  auto& dataSet = m_rootInterface.get2HitDataSet();
124  dataSet.expNo = m_expNo;
125  dataSet.runNo = m_runNo;
126  dataSet.evtNo = m_evtNo;
127  dataSet.trackNo = aTC.getTrackID();
128  dataSet.pdg = aTC.getPDG();
129  dataSet.secIDs.outer = outerIt->getSectorID().getFullSecID();
130  dataSet.secIDs.inner = innerIt->getSectorID().getFullSecID();
131 
132  // create data for each filterType:
134  newHitPair.outer = &(*outerIt);
135  newHitPair.inner = &(*innerIt);
136  m_filterMill.grindData2Hit(newHitPair, collectedResults);
137 
138  // fill data for each filter type:
139  for (const auto& entry : collectedResults) {
140  B2DEBUG(25, "SecMapTrainer::process2HitCombinations: filter/value: " << entry.first << "/" << entry.second);
141  dataSet.setValueOfFilter(entry.first, entry.second);
142  ++nValues;
143  }
145  collectedResults.clear();
146  ++outerIt;
147  ++innerIt;
148  }
149  return nValues;
150  }
151 
152 
153 
156  {
157  unsigned nValues = 0;
158  B2DEBUG(20, "SecMapTrainer::process3HitCombinations: nHits/trackID/pdg: " << aTC.size() << "/" << aTC.getTrackID() << "/" <<
159  aTC.getPDG());
160  if (aTC.size() < 3) { return nValues; }
161 
162  // the iterators mark the hits to be used:
164  SecMapTrainerTC::ConstIterator centerIt = ++aTC.outermostHit();
165  SecMapTrainerTC::ConstIterator innerIt = ++(++aTC.outermostHit());
166 
167  // loop over all 3-hit-combis, collect data for each filterType and store it in root-tree:
168  std::vector<std::pair<std::string, double> > collectedResults;
169  for (; innerIt != aTC.innerEnd();) {
170  B2DEBUG(20, "SecMapTrainer::process3HitCombinations: outer-/center-/innerHitSecID: " << outerIt->getSectorIDString() <<
171  "/" << centerIt->getSectorIDString() <<
172  "/" << innerIt->getSectorIDString());
173 
174  auto& dataSet = m_rootInterface.get3HitDataSet();
175  dataSet.expNo = m_expNo;
176  dataSet.runNo = m_runNo;
177  dataSet.evtNo = m_evtNo;
178  dataSet.trackNo = aTC.getTrackID();
179  dataSet.pdg = aTC.getPDG();
180  dataSet.secIDs.outer = outerIt->getSectorID().getFullSecID();
181  dataSet.secIDs.center = centerIt->getSectorID().getFullSecID();
182  dataSet.secIDs.inner = innerIt->getSectorID().getFullSecID();
183 
184  // create data for each filterType:
186  newHitTriplet.outer = &(*outerIt);
187  newHitTriplet.center = &(*centerIt);
188  newHitTriplet.inner = &(*innerIt);
189  m_filterMill.grindData3Hit(newHitTriplet, collectedResults);
190 
191  // fill data for each filter type:
192  for (const auto& entry : collectedResults) {
193  B2DEBUG(25, "SecMapTrainer::process3HitCombinations: filter/value: " << entry.first << "/" << entry.second);
194  dataSet.setValueOfFilter(entry.first, entry.second);
195  ++nValues;
196  }
198  collectedResults.clear();
199  ++outerIt;
200  ++centerIt;
201  ++innerIt;
202  }
203  return nValues;
204  }
205 
206 
209  const std::vector<std::pair< FullSecID, const SpacePoint*> >& goodSPs,
210  unsigned tcID, double pTValue, int pdgCode)
211  {
212  B2DEBUG(20, "SecMapTrainer::convertSPTC: nGoodHits: " << goodSPs.size());
213 
214  SecMapTrainerTC newTrack(tcID, pTValue, pdgCode);
215 
216  for (const auto& secIDAndSPpair : goodSPs) {
217  FullSecID fullSecID = secIDAndSPpair.first;
218  B2DEBUG(20, "SecMapTrainer::convertSPTC: found fullSecID: " << fullSecID.getFullSecString());
219 
220  newTrack.addHit(SecMapTrainerHit(fullSecID, *secIDAndSPpair.second));
221  }
222 
223  // add vertex (but without real vertexPosition, since origin is assumed)
224  SecMapTrainerHit newVirtualHit(FullSecID(), m_config.vIP);
225 
226  newTrack.addHit(std::move(newVirtualHit));
227 
228  m_tcs.push_back(std::move(newTrack));
229  }
230 
231 
232  public:
233 
235  explicit SecMapTrainer(const std::string& setupName, const std::string& appendix = "") :
236  m_nameSetup(setupName),
238  m_factory(
239  m_config.vIP.X(),
240  m_config.vIP.Y(),
241  m_config.vIP.Z(),
242  m_config.mField),
243 
244  m_filterMill(),
245  m_rootInterface(m_config.secMapName, appendix),
246  m_expNo(std::numeric_limits<unsigned>::max()),
247  m_runNo(std::numeric_limits<unsigned>::max()),
248  m_evtNo(std::numeric_limits<unsigned>::max())
249  {
250  // stretch the cuts:
251 // m_config.pTCuts.first -= m_config.pTCuts.first * m_config.pTSmear;
252 // m_config.pTCuts.second += m_config.pTCuts.second * m_config.pTSmear;
255  }
256 
257 
259  void initialize()
260  {
261  // prepare the filters!
262  // 2 space points:
264 
265  std::vector< std::string> twoHitFilters;
266  for (const auto& filterNameToFunction : TwoSPfilterNamesToFunctions)
267  twoHitFilters.push_back(filterNameToFunction.first);
268 
269  m_rootInterface.initialize2Hit(twoHitFilters);
270  for (auto& nameToFunction : TwoSPfilterNamesToFunctions)
271  m_filterMill.add2HitFilter(nameToFunction);
272 
273 
274  // 3 space points:
275  auto ThreeSPfilterNamesToFunctions(SelectionVariableNamesToFunctions(
277 
278  std::vector< std::string> threeHitFilters;
279  for (const auto& filterNameToFunction : ThreeSPfilterNamesToFunctions)
280  threeHitFilters.push_back(filterNameToFunction.first);
281 
282  m_rootInterface.initialize3Hit(threeHitFilters);
283  for (auto& nameToFunction : ThreeSPfilterNamesToFunctions)
284  m_filterMill.add3HitFilter(nameToFunction);
285  for (auto& nameToFunction : ThreeSPfilterNamesToFunctions)
286  m_filterMill.add3HitFilter(nameToFunction);
287 
288 
289  // 4 space points apparently unused
290  // m_rootInterface.initialize4Hit(m_config.fourHitFilters);
291 
292  // auto FourSPfilterNamesToFunctions( SelectionVariableNamesToFunctions(
293  // VXDTFFilters<SecMapTrainerHit>::fourHitFilter_t() ));
294 
295  // std::vector< std::string> fourHitFilters;
296  // for (const auto& filterNameToFunction :FourSPfilterNamesToFunctions )
297  // fourHitFilters.push_back( filterNameToFunction.first );
298 
299  // m_rootInterface.initialize4Hit(fourHitFilters);
300  // for (auto& nameToFunction : FourSPfilterNamesToFunctions)
301  // m_filterMill.add4HitFilter(nameToFunction);
302 
303  // prevent further modifications:
304  m_filterMill.lockMill();
305  }
306 
308 // void terminate(TFile* file)
309 // { m_rootInterface.write(file); }
310  void terminate()
311  { m_rootInterface.write(); }
312 
314  void initializeEvent(int expNo, int runNo, int evtNo)
315  {
316  m_expNo = expNo;
317  m_runNo = runNo;
318  m_evtNo = evtNo;
319  }
320 
321 
323  const SectorMapConfig& getConfig() { return m_config; }
324 
325 
327  const std::string getSetupName() { return m_nameSetup; }
328 
333  bool storeTC(const SpacePointTrackCand& tc, unsigned iD)
334  {
335  B2DEBUG(20, "SecMapTrainer::storeTC: nHits/threshold: " << tc.getNHits() << "/" << m_config.nHitsMin);
336  // catch TCS which are too short in any case
337  if (tc.getNHits() < m_config.nHitsMin) return false;
338 
339  B2DEBUG(20, "SecMapTrainer::storeTC: hasHitsOnSameSensor: " << tc.hasHitsOnSameSensor());
340  // catch TCs where more than one hit was on the same sensor
341  if (tc.hasHitsOnSameSensor()) return false;
342 
343  // catch TCS where particle type is wrong
344  bool found = false;
345  for (const auto& pdg : m_config.pdgCodesAllowed) {
346  if (tc.getPdgCode() == pdg) found = true;
347  }
348  if (found == false and m_config.pdgCodesAllowed.empty() == false) return false;
349 
350  // check if momentum of TC is within range:
351  auto pT = tc.getMomSeed().Rho();
352  B2DEBUG(20, "SecMapTrainer::storeTC: pT/thresholdmin/-max: " << pT << "/" << m_config.pTmin << "/" <<
353  m_config.pTmax);
354  if (m_config.pTmin > pT or m_config.pTmax < pT) return false;
355 
356  // catch tracks which start too far away from orign
357  B2Vector3D distance2IP = m_config.vIP - tc.getPosSeed();
358  B2DEBUG(20, "SecMapTrainer::storeTC: distance2IP/thresholdXY/-Z: " << distance2IP.Mag() << "/" << m_config.seedMaxDist2IPXY << "/"
360  if (m_config.seedMaxDist2IPXY > 0
361  and m_config.seedMaxDist2IPXY < distance2IP.Perp()) return false;
362  if (m_config.seedMaxDist2IPZ > 0
363  and m_config.seedMaxDist2IPXY < distance2IP.Z()) return false;
364 
365  // collect hits which fullfill all given tests
366  std::vector<std::pair<FullSecID, const SpacePoint*> > goodSPs;
367  for (const SpacePoint* aSP : tc.getHits()) {
368  if (!acceptHit(*aSP)) continue;
369 
370  FullSecID fSecID = m_filtersContainer.getFilters(m_nameSetup)->getFullID(aSP->getVxdID(),
371  aSP->getNormalizedLocalU(), aSP->getNormalizedLocalV());
372  if (fSecID.getFullSecID() == std::numeric_limits<unsigned int>::max())
373  { B2ERROR("a secID for spacePoint not found!"); continue; }
374 
375  goodSPs.push_back({fSecID, aSP});
376  }
377 
378  // catch tracks which have not enough accepted hits.
379  B2DEBUG(20, "SecMapTrainer::storeTC: the TC has now nHits/threshold: " << goodSPs.size() << "/" << m_config.nHitsMin);
380  if (goodSPs.size() < m_config.nHitsMin || goodSPs.size() == 0) return false;
381 
382  // want to have hits going from outer to inner ones
383  if (tc.isOutgoing()) std::reverse(goodSPs.begin(), goodSPs.end());
384 
385 
386  // enfoce a direction in the layer numbering, because else this could generate loops in the sectormap
387  int prevLayerNum = goodSPs.at(0).second->getVxdID().getLayerNumber();
388  for (auto& spCand : goodSPs) {
389  int thisLayerNum = spCand.second->getVxdID().getLayerNumber();
390  // allow same layer
391  if (thisLayerNum > prevLayerNum) {
392  B2DEBUG(20, "Rejected TC due to layer ordering of SPs! previous layer: " << prevLayerNum << " this layer: " << thisLayerNum);
393  return false;
394  }
395  prevLayerNum = thisLayerNum;
396  }
397 
398 
399  convertSP2TC(goodSPs, iD, tc.getMomSeed().Rho(), tc.getPdgCode());
400 
401  return true;
402  }
403 
404 
405 
408  /*
409  FullSecID createSecID(VxdID iD, double uVal, double vVal)
410  {
411  // TODO replace by new secMap-design-approach
412  std::vector<double> uTemp = {0.};
413  uTemp.insert(uTemp.end(), m_config.uSectorDivider.begin(), m_config.uSectorDivider.end());
414  std::vector<double> vTemp = {0.};
415  vTemp.insert(vTemp.end(), m_config.vSectorDivider.begin(), m_config.vSectorDivider.end());
416  auto secID = SectorTools::calcSecID(uTemp, vTemp, {uVal, vVal});
417  if (secID == std::numeric_limits<unsigned short>::max())
418  return FullSecID(std::numeric_limits<unsigned int>::max());
419  return FullSecID(iD, false, secID);
420  }
421  */
422 
423 
426  unsigned processTracks()
427  {
428  unsigned n2HitResults = 0;
429  unsigned n3HitResults = 0;
430  unsigned nTracksProcessed = m_tcs.size();
431 
432  for (const auto& tc : m_tcs) {
433  // two hit:
434  n2HitResults += process2HitCombinations(tc);
435  // three hit:
436  n3HitResults += process3HitCombinations(tc);
437  }
438 
439  m_tcs.clear();
440  B2DEBUG(25, "SecMapTrainer::processTracks: nStoredValues for 2-/3-hit: " << n2HitResults << "/" << n3HitResults);
441 
442  return nTracksProcessed;
443  }
444  };
446 }
447 
DataType Z() const
access variable Z (= .at(2) without boundary check)
Definition: B2Vector3.h:435
DataType Mag() const
The magnitude (rho in spherical coordinate system).
Definition: B2Vector3.h:159
DataType Perp() const
The transverse component (R in cylindrical coordinate system).
Definition: B2Vector3.h:200
Small class which stores the filters/selectionVariables to be used for a secMap and has an interface ...
Definition: FilterMill.h:25
This class contains everything needed by the VXDTF that is not going to change during a RUN,...
static FiltersContainer & getInstance()
one and only way to access the singleton object
Class to identify a sector inside of the VXD.
Definition: FullSecID.h:33
std::string getFullSecString() const
returns the FullSecID coded as string compatible to secIDs stored in the xml-sectormaps
Definition: FullSecID.cc:116
unsigned int getFullSecID() const
returns the FullSecID coded as integer for further use (can be reconverted to FullSecID by using Full...
Definition: FullSecID.h:150
To be used as an interface to root-stuff.
void fill3Hit()
fill three-hit-combinations in tree, triggers an Error if values not set yet.
FilterValueDataSet< SecIDPair > & get2HitDataSet()
returns a reference to the 2-hit-dataset so one can set the relevant values.
void initialize3Hit(std::vector< std::string > filterNames)
initialize the RawSecMapRootInterface for three-hit-combinations (to be called in Module::initialize(...
void fill2Hit()
fill two-hit-combinations in tree, triggers an Error if values not set yet.
void write()
write all trees to file at end of processing.
void initialize2Hit(std::vector< std::string > filterNames)
initialize the RawSecMapRootInterface for two-hit-combinations (to be called in Module::initialize().
FilterValueDataSet< SecIDTriplet > & get3HitDataSet()
returns a reference to the 3-hit-dataset so one can set the relevant values.
simple Hit class used for sectorMap-training.
simple Hit class used for sectorMap-training.
unsigned size() const
returns number of hits attached to curren track.
ConstIterator innerEnd() const
returns the iterator-position pointing after the innermost hit.
int getTrackID() const
returns indexNumber of current track.
int getPDG() const
returns pdgCode of current track.
void addHit(SecMapTrainerHit hit)
adds hit to Track.
typename std::vector< SecMapTrainerHit >::const_iterator ConstIterator
typedef for more readable iterator-type
ConstIterator outermostHit() const
returns the iterator-position pointing to the outermost hit.
This class contains all relevant tools for training a VXDTFFilters.
Definition: SecMapTrainer.h:43
FilterFactoryType m_factory
A factory taking care of having the correct filters prepared for secMapTraining.
Definition: SecMapTrainer.h:57
FilterMill< SecMapTrainerHit > m_filterMill
Stores the prepared filters and applies them on given hit-combinations.
Definition: SecMapTrainer.h:60
void initialize()
initialize the trainer (to be called in Module::initialize().
void initializeEvent(int expNo, int runNo, int evtNo)
Initialize event.
const std::string getSetupName()
returns the name of the setup used for this trainer
void convertSP2TC(const std::vector< std::pair< FullSecID, const SpacePoint * > > &goodSPs, unsigned tcID, double pTValue, int pdgCode)
converts the SpacePoints into a SecMapTrainerTC and stores it to m_TCs
bool acceptHit(const SpacePoint &hit)
checks if given Hit is acceptable for this trainer.
Definition: SecMapTrainer.h:87
void terminate()
initialize the trainer (to be called in Module::terminate().
unsigned m_runNo
contains current run number.
Definition: SecMapTrainer.h:76
const SectorMapConfig & getConfig()
returns configuration.
RawSecMapRootInterface m_rootInterface
Interface for nice and neat storing in root-ttree.
Definition: SecMapTrainer.h:64
unsigned process3HitCombinations(const SecMapTrainerTC &aTC)
processes all three-hit-combinations of given TC and stores their results.
FiltersContainer< SpacePoint > & m_filtersContainer
a reference to the singleton FiltersContainer used for this training.
Definition: SecMapTrainer.h:50
SectorMapConfig m_config
Contains all relevant configurations needed for training a sectorMap.
Definition: SecMapTrainer.h:54
std::vector< SecMapTrainerTC > m_tcs
contains tcs of event, reset after each event.
Definition: SecMapTrainer.h:68
unsigned m_expNo
contains current experiment number.
Definition: SecMapTrainer.h:72
unsigned processTracks()
for given normalized local variables and VxdID a FullSecID is determined.
SecMapTrainer(const std::string &setupName, const std::string &appendix="")
constructor.
const std::string m_nameSetup
name of the setting to be used for this training
Definition: SecMapTrainer.h:46
unsigned m_evtNo
contains current event number.
Definition: SecMapTrainer.h:80
bool storeTC(const SpacePointTrackCand &tc, unsigned iD)
checks if given TC is acceptable for this trainer and store it if it is accepted.
unsigned process2HitCombinations(const SecMapTrainerTC &aTC)
processes all two-hit-combinations of given TC and stores their results.
Storage for (VXD) SpacePoint-based track candidates.
const ROOT::Math::XYZVector getPosSeed() const
get position seed as ROOT::Math::XYZVector
const ROOT::Math::XYZVector getMomSeed() const
get momentum seed as ROOT::Math::XYZVector
unsigned int getNHits() const
get the number of hits (space points) in the track candidate
int getPdgCode() const
get pdg code
const std::vector< const Belle2::SpacePoint * > & getHits() const
get hits (space points) of track candidate
bool hasHitsOnSameSensor() const
Check if the SpacePointTrackCand contains consecutive SpacePoints that are on the same sensor WARNING...
bool isOutgoing() const
check if particle is outgoing (simply returns member m_flightDirection)!
SpacePoint typically is build from 1 PXDCluster or 1-2 SVDClusters.
Definition: SpacePoint.h:42
Class that contains all the static sectors to which the filters are attached.
Definition: VXDTFFilters.h:63
std::unordered_map< std::string, typename Variable::functionType > SelectionVariableNamesToFunctions(Belle2::Filter< Variable, Range, Options... >)
Return a map from the SelectionVariable name to the SelectionVariable function of the Variable used i...
Abstract base class for different kinds of events.
small struct containing pointers to two hits.
Definition: FilterMill.h:73
const PointType * outer
outer hit.
Definition: FilterMill.h:74
const PointType * inner
inner hit.
Definition: FilterMill.h:75
small struct containing pointers to three hits.
Definition: FilterMill.h:79
const PointType * center
center hit.
Definition: FilterMill.h:81
const PointType * outer
outer hit.
Definition: FilterMill.h:80
const PointType * inner
inner hit.
Definition: FilterMill.h:82
simple struct containing all the configuration data needed for the SecMapTrainer.
double pTmin
stores pTCuts for min pT allowed for this .
double pTSmear
allows smearing of the cuts.
std::vector< int > pdgCodesAllowed
Stores all the pdgCodes which are allowed to be used by the SecMap.
double seedMaxDist2IPXY
Stores a cut for maximum distance of the seed in xy of the given virtual IP.
B2Vector3D vIP
Stores the position of the assumed position of the interaction point - The virtual IP.
double seedMaxDist2IPZ
Stores a cut for maximum distance of the seed in z of the given virtual IP.
double pTmax
stores pTCuts for min (.first) and max (.second) ptCut.
unsigned nHitsMin
Stores the minimal number of hits a TC must have to be accepted as TC (vIP-Hits are ignored).
std::vector< int > allowedLayers
stores allowed layers to be used (including virtual IP with layer 0).