Belle II Software  release-06-01-15
SPTCRefereeModule.cc
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 #include <tracking/modules/spacePointCreator/SPTCRefereeModule.h>
10 #include <tracking/dataobjects/RecoTrack.h>
11 
12 #include <framework/datastore/StoreArray.h>
13 #include <framework/datastore/StoreObjPtr.h>
14 #include <framework/dataobjects/EventMetaData.h>
15 
16 #include <tracking/spacePointCreation/SpacePoint.h>
17 #include <pxd/dataobjects/PXDTrueHit.h>
18 #include <svd/dataobjects/SVDTrueHit.h>
19 #include <vxd/dataobjects/VxdID.h>
20 
21 #include <framework/geometry/B2Vector3.h> // use TVector3 instead?
22 #include <boost/range/adaptor/reversed.hpp> // for ranged based loops in reversed order
23 
24 using namespace Belle2;
25 using namespace std;
26 
27 REG_MODULE(SPTCReferee) // register the module
28 
30 {
31  setDescription("Module that does some sanity checks on SpacePointTrackCands to prevent some problematic cases to be "
32  "forwarded to other modules that rely on 'unproblematic' cases (e.g. FilterCalculator). "
33  "Different checks can be enabled by setting the according flags. Using MC information for "
34  "the tests can also be switched on/off for tests where MC information can be helpful.");
35  setPropertyFlags(c_ParallelProcessingCertified);
36 
37  // names
38  addParam("sptcName", m_PARAMsptcName,
39  "Container name of the SpacePointTrackCands to be checked (input)",
40  m_PARAMsptcName);
41  addParam("newArrayName", m_PARAMnewArrayName,
42  "Container name of SpacePointTrackCands if 'storeNewArray' is set to true",
43  m_PARAMnewArrayName);
44  addParam("curlingSuffix", m_PARAMcurlingSuffix,
45  "Suffix that will be used to get a name for the StoreArray in which the trackStubs that are obtained by "
46  "splitting a curling SPTC get stored. NOTE: If 'storeNewArray' is set to true, "
47  "this will not be used and all output SPTCs will be in the same Array!",
48  m_PARAMcurlingSuffix);
49 
50  // flags
51  addParam("checkSameSensor", m_PARAMcheckSameSensor,
52  "Check if two subsequent SpacePoints are on the same sensor",
53  m_PARAMcheckSameSensor);
54  addParam("checkMinDistance", m_PARAMcheckMinDistance,
55  "Check if two subsequent SpacePoints are seperated by more than 'minDistance'",
56  m_PARAMcheckMinDistance);
57  addParam("checkCurling", m_PARAMcheckCurling,
58  "Check the SpacePointTrackCand for curling behaviour and mark it as curling if it does",
59  m_PARAMcheckCurling);
60  addParam("splitCurlers", m_PARAMsplitCurlers,
61  "Split curling SpacePointTrackCands and save the TrackStubs in seperate StoreArrays",
62  m_PARAMsplitCurlers);
63  addParam("keepOnlyFirstPart", m_PARAMkeepOnlyFirstPart,
64  "Keep only the first part of a curling SpacePointTrackCand (e.g. when only this is needed)",
65  m_PARAMkeepOnlyFirstPart);
66  addParam("useMCInfo", m_PARAMuseMCInfo,
67  "Set to true if the use of MC information (e.g. from underlying TrueHits) for the checks is wanted, "
68  "and to false if the checks should all be done with information that can be obtained from "
69  "SpacePoints directly. NOTE: the tests without MC information have to be developed first!",
70  m_PARAMuseMCInfo);
71  addParam("kickSpacePoint", m_PARAMkickSpacePoint,
72  "Set to true if only the 'problematic' SpacePoint shall be kicked and not the whole SpacePointTrackCand",
73  m_PARAMkickSpacePoint);
74  addParam("storeNewArray", m_PARAMstoreNewArray,
75  "Set to true if the checked SpacePointTrackCands should be stored in a new StoreArray."
76  "WARNING: all previously registered relations get lost in this way!",
77  m_PARAMstoreNewArray);
78 
79  // other
80  addParam("minDistance", m_PARAMminDistance,
81  "Minimal Distance [cm] that two subsequent SpacePoints have to be seperated if 'checkMinDistance' is enabled",
82  m_PARAMminDistance);
83  addParam("setOrigin", m_PARAMsetOrigin, "WARNING: still need to find out the units that are used internally! "
84  "Reset origin to given point. Used for determining the direction of flight of a particle for a "
85  "given hit. Needs to be reset for e.g. testbeam, where origin is not at (0,0,0)",
86  m_PARAMsetOrigin);
87 
88  addParam("minNumSpacePoints", m_PARAMminNumSpacePoints,
89  "minimum number of space points that a track candidate has to "
90  "contain (added later, set to 0 to reproduce old behavior",
91  m_PARAMminNumSpacePoints);
92 
93  addParam("checkIfFitted", m_PARAMcheckIfFitted,
94  "If true a flag is set in the SpacePointTrackCandidate if any related RecoTrack "
95  "with successful track fit is found",
96  m_PARAMcheckIfFitted);
97 
98  // initialize counters (cppcheck)
99  initializeCounters();
100 }
101 
102 // ======================================================================= INITIALIZE =============================================
103 void SPTCRefereeModule::initialize()
104 {
105  B2INFO("SPTCReferee::initialize(): ------------------------------------------------ ");
106  // check if StoreArray of SpacePointTrackCands is her
108  inputSpacePoints.isRequired(m_PARAMsptcName);
109 
110  // register new StoreArray
111  if (m_PARAMstoreNewArray) {
114  newStoreArray.registerRelationTo(inputSpacePoints, DataStore::c_Event, DataStore::c_DontWriteOut);
115  } else {
117  B2DEBUG(20, "StoreArray name of the curling parts: " << m_curlingArrayName);
120  newStoreArray.registerRelationTo(inputSpacePoints, DataStore::c_Event, DataStore::c_DontWriteOut);
121  }
122 
123  // sanity checks on the other parameters
125  if (m_PARAMminDistance < 0) {
126  B2WARNING("minDistance set to value below 0: " << m_PARAMminDistance <<
127  ", Taking the absolute value and resetting 'minDistance' to that!");
129  }
130  }
131 
132  B2DEBUG(20, "Provided Parameters: checkSameSensor - " << m_PARAMcheckSameSensor << ", checkMinDistance - " <<
134  << ", checkCurling - " << m_PARAMcheckCurling << ", splitCurlers - " << m_PARAMsplitCurlers << ", keepOnlyFirstPart - " <<
135  m_PARAMkeepOnlyFirstPart << ", useMCInfo - " << m_PARAMuseMCInfo << ", kickSpacePoint - " << m_PARAMkickSpacePoint);
136  if (m_PARAMsetOrigin.size() != 3) {
137  B2WARNING("CurlingTrackCandSplitter::initialize: Provided origin is not a 3D point! Please provide 3 values (x,y,z). "
138  "Rejecting user input and setting origin to (0,0,0) for now!");
139  m_PARAMsetOrigin.clear();
140  m_PARAMsetOrigin.assign(3, 0);
141  }
143  B2DEBUG(20, "Set origin to (x,y,z): (" << m_origin.X() << "," << m_origin.Y() << "," << m_origin.Z() << ")");
144 
146 }
147 
148 // ======================================================================== EVENT =================================================
150 {
151  StoreObjPtr<EventMetaData> eventMetaDataPtr("EventMetaData", DataStore::c_Event);
152  const int eventCtr = eventMetaDataPtr->getEvent();
153  B2DEBUG(20, "Processing event " << eventCtr << " -----------------------");
154 
156  const int nTCs = trackCands.getEntries();
157 
158  m_totalTrackCandCtr += nTCs;
159 
160  B2DEBUG(20, "Found " << nTCs << " SpacePointTrackCands in Array " << trackCands.getName() << " for this event");
161 
162  for (int iTC = 0; iTC < nTCs; ++iTC) { // loop over all TrackCands
163  SpacePointTrackCand* trackCand = trackCands[iTC];
164  B2DEBUG(20, "Processing SpacePointTrackCand " << iTC << ": It has " << trackCand->getNHits() << " SpacePoints in it");
165 
166  if (LogSystem::Instance().isLevelEnabled(LogConfig::c_Debug, 200, PACKAGENAME())) { trackCand->print(); }
167  B2DEBUG(20, "refereeStatus of TrackCand before tests: " << trackCand->getRefereeStatus() << " -> " <<
168  trackCand->getRefereeStatusString());
169 
170  // if all tests will be performed -> add checkedByReferee status to the SPTC,
171  // CAUTION: if there are new tests this has to be updated!!!, WARNING: if curling check fails,
172  // checkedForCurling will return false but hasRefereeStatus(c_checkedByReferee) will return true after this module!
175  }
176  bool allChecksClean = true; // assume that all tests will be passed, change to false if one of them fails
177  CheckInfo prevChecksInfo;
178 
179 
180  // added check for the number of space points in the track candidate
181  if ((int)(trackCand->getNHits()) < m_PARAMminNumSpacePoints) {
182  allChecksClean = false;
183  }
184 
185 
186  // set a flag if a fitted recotrack is found for that trackcand
187  if (m_PARAMcheckIfFitted) {
188  // take any related recotrack
189  RelationVector<RecoTrack> relatedRecoTracks = trackCand->getRelationsTo<RecoTrack>("ALL");
190  if (relatedRecoTracks.size() >= 1) {
191  // assume that there is only one!
192  if (relatedRecoTracks[0]->wasFitSuccessful()) {
194  } else {
195  allChecksClean = false;
196  B2DEBUG(20, "Found RecoTrack was not fitted! Will not use this track candidate for training.");
197  }
198  } else {
199  allChecksClean = false;
200  B2DEBUG(20, "No related RecoTrack found. Will not use that track candidate for training");
201  }
202  }
203 
204 
205  // check same sensors if desired
207  const std::vector<int> sameSensorInds = checkSameSensor(trackCand);
208  std::get<0>(prevChecksInfo) = sameSensorInds;
209  if (!sameSensorInds.empty()) {
210  m_SameSensorCtr++;
211  allChecksClean = false;
212  // assign the actually removed indices to the prevChecksInfo
213  if (m_PARAMkickSpacePoint) {
214  std::get<0>(prevChecksInfo) = removeSpacePoints(trackCand, sameSensorInds);
215  } else {
216  // only add status if the SpacePoints on the same sensors have not been removed!
218  }
219  } else {
220  B2DEBUG(20, "Found no two subsequent SpacePoints on the same sensor for this SpacePointTrackCand ("
221  << iTC << " in Array " << trackCands.getName() << ")");
222  }
224  B2DEBUG(20, "refereeStatus of TrackCand after checkSameSensor " << trackCand->getRefereeStatus() << " -> " <<
225  trackCand->getRefereeStatusString());
226  }
227 
228 
229  // check min distance if desired
231  const std::vector<int> lowDistanceInds = checkMinDistance(trackCand, m_PARAMminDistance);
232  std::get<1>(prevChecksInfo) = lowDistanceInds;
233  if (!lowDistanceInds.empty()) {
235  allChecksClean = false;
236  // assign the actually removed indices to the prevChecksInfo
237  if (m_PARAMkickSpacePoint) {
238  std::get<1>(prevChecksInfo) = removeSpacePoints(trackCand, lowDistanceInds);
239  } else {
240  // only add status if the SpacePoints not far enough apart have not been removed!
242  }
243  } else {
244  B2DEBUG(20, "Found no two subsequent SpacePoints that were closer than " << m_PARAMminDistance <<
245  " cm together for this SpacePointTrackCand (" << iTC << " in Array " << trackCands.getName() << ")");
246  }
248  B2DEBUG(20, "refereeStatus of TrackCand after checkMinDistance " << trackCand->getRefereeStatus() << " -> " <<
249  trackCand->getRefereeStatusString());
250  }
251 
252  // vector of TrackStubs that shall be saved to another StoreArray
253  std::vector<SpacePointTrackCand> curlingTrackStubs;
254  // check curling if desired
255  if (m_PARAMcheckCurling) {
256  // setting the TrackStubIndex to 0 implies that this trackCand has been checked for curling.
257  // (If there is something wrong in the curling check this value is reset to -1!)
258  trackCand->setTrackStubIndex(0);
259  const std::vector<int> curlingSplitInds = checkCurling(trackCand, m_PARAMuseMCInfo);
260  if (!curlingSplitInds.empty()) {
261  if (!(curlingSplitInds.at(0) == 0 && curlingSplitInds.size() == 1)) {
262  // this means essentially that the direction of flight for this SPTC is inwards for all SpacePoints!
264  allChecksClean = false;
265  if (m_PARAMsplitCurlers) {
266  curlingTrackStubs = splitTrackCand(trackCand, curlingSplitInds, m_PARAMkeepOnlyFirstPart, prevChecksInfo, m_PARAMkickSpacePoint);
267  if (curlingTrackStubs.empty()) {
268  B2ERROR("The vector returned by splitTrackCand is empty!");
269  } // safety measure
270  }
271  // set this to the original SPTC only after splitting to avoid having this status in the trackStubs
273  } else {
274  B2DEBUG(20, "The only entry in the return vector of checkCurling is 0! The direction of flight is inwards for the whole SPTC!");
275  trackCand->setFlightDirection(false);
276  m_allInwardsCtr++;
277  }
278  } else {
279  B2DEBUG(20, "SpacePointTrackCand " << trackCand->getArrayIndex() << " is not curling!");
280  }
281  B2DEBUG(20, "refereeStatus of TrackCand after checkCurling " << trackCand->getRefereeStatus() << " -> " <<
282  trackCand->getRefereeStatusString());
283  }
284 
285  // PROCESSING AFTER CHECKS
286  if (allChecksClean) trackCand->addRefereeStatus(SpacePointTrackCand::c_checkedClean);
287 
288  B2DEBUG(20, "referee Status of SPTC after referee module: " << trackCand->getRefereeStatus() << " -> " <<
289  trackCand->getRefereeStatusString());
290  if (LogSystem::Instance().isLevelEnabled(LogConfig::c_Debug, 200, PACKAGENAME())) { trackCand->print();}
291 
292  // store in appropriate StoreArray
293  if (m_PARAMstoreNewArray) {
295  if (!trackCand->isCurling()) { copyToNewStoreArray(trackCand, newArray); }
296  else {
297  for (const SpacePointTrackCand& trackStub : curlingTrackStubs) { addToStoreArray(trackStub, newArray, trackCand); }
298  }
299  } else {
301  if (trackCand->isCurling()) {
302  for (const SpacePointTrackCand& trackStub : curlingTrackStubs) { addToStoreArray(trackStub, curlingArray, trackCand); }
303  }
304  }
305  }
306 }
307 
308 // ============================================================================= TERMINATE ========================================
310 {
311  // TODO: info output more sophisticated
312  stringstream summary;
314  summary << "Checked for consecutive SpacePoints on same sensor and found "
315  << m_SameSensorCtr << " TrackCands showing this behavior.\n";
316  }
318  summary << "Checked for minimal distance between two consecutive SpacePoints and found "
319  << m_minDistanceCtr << " TrackCands with SpacePoints not far enough apart.\n";
320  }
321  if (m_PARAMkickSpacePoint) {
322  summary << m_kickedSpacePointsCtr << " SpacePoints have been removed from SpacePointTrackCands\n";
323  }
324  if (m_PARAMcheckCurling) {
325  summary << m_curlingTracksCtr << " SPTCs were curling. Registered "
326  << m_regTrackStubsCtr << " track stubs. 'splitCurlers' was set to "
327  << m_PARAMsplitCurlers << ", 'keepOnlyFirstPart' was set to "
328  << m_PARAMkeepOnlyFirstPart << ". There were "
329  << m_allInwardsCtr << " SPTCs that had flight direction 'inward' for all SpacePoints in them";
330  }
331 
332  B2INFO("SPTCRefere::terminate(): Module got " << m_totalTrackCandCtr << " SpacePointTrackCands. \n" << summary.str());
333 
335  B2WARNING("The curling checking without MC Information is at the moment at a very crude and unsophisticated state. "
336  "If you have MC information available you should use it to do this check!");
337  }
338 }
339 
340 // ====================================================================== CHECK SAME SENSORS ======================================
342 {
343  B2DEBUG(20, "Checking SpacePointTrackCand " << trackCand->getArrayIndex() << " from Array " << trackCand->getArrayName() <<
344  " for consecutive SpacePoints on the same sensor");
345  std::vector<int> sameSensorInds; // return vector
346 
347  std::vector<const SpacePoint*> spacePoints = trackCand->getHits();
348 
349  // catch cases where the TC has no space points! (Yes that happens!)
350  if (spacePoints.size() == 0) return sameSensorInds;
351 
352  VxdID lastSensorId = spacePoints.at(0)->getVxdID();
353 
354  for (unsigned int iSp = 1; iSp < spacePoints.size(); ++iSp) {
355  VxdID sensorId = spacePoints.at(iSp)->getVxdID();
356  B2DEBUG(20, "Checking SpacePoint " << iSp << ". (ArrayIndex " << spacePoints.at(iSp)->getArrayIndex() <<
357  ") SensorId of this SpacePoint: " << sensorId << ", SensorId of last SpacePoint: " << lastSensorId);
358  if (sensorId == lastSensorId) {
359  // push back the index of the first SpacePoint (50:50 chance of getting the right one without further testing) -> retrieving the other index is no big science from this index!!
360  sameSensorInds.push_back(iSp - 1);
361  B2DEBUG(20, "SpacePoint " << iSp << " and " << iSp - 1 << " are on the same sensor: " << sensorId);
362  }
363  lastSensorId = sensorId;
364  }
365 
366  return sameSensorInds;
367 }
368 
369 // ========================================================================= CHECK MIN DISTANCE ===================================
370 const std::vector<int> SPTCRefereeModule::checkMinDistance(Belle2::SpacePointTrackCand* trackCand, double minDistance)
371 {
372  B2DEBUG(20, "Checking the distances between consecutive SpacePoints for SpacePointTrackCand " << trackCand->getArrayIndex() <<
373  " from Array " << trackCand->getArrayIndex());
374  std::vector<int> lowDistanceInds; // return vector
375 
376  std::vector<const SpacePoint*> spacePoints = trackCand->getHits();
377 
378  // catch case where the track candidate has no spacepoints
379  if (spacePoints.size() == 0) return lowDistanceInds;
380 
381  B2Vector3F oldPosition = spacePoints.at(0)->getPosition();
382 
383  for (unsigned int iSp = 1; iSp < spacePoints.size(); ++iSp) {
384  B2Vector3F position = spacePoints.at(iSp)->getPosition();
385  B2Vector3F diffPos = oldPosition - position;
386  B2DEBUG(20, "Position of SpacePoint " << iSp << " (ArrayIndex " << spacePoints.at(iSp)->getArrayIndex() << "): (" << position.X() <<
387  "," << position.Y() << "," << position.Z() << "), Position of SpacePoint " << iSp - 1 << ": (" << oldPosition.X() << "," <<
388  oldPosition.Y() << "," << oldPosition.Z() << ") --> old - new = (" << diffPos.X() << "," << diffPos.Y() << "," << diffPos.Z() <<
389  ")");
390 
391  if (diffPos.Mag() <= minDistance) {
392  B2DEBUG(20, "Position difference is " << diffPos.Mag() << " but minDistance is set to " << minDistance << ". SpacePoints: " << iSp
393  << " and " << iSp - 1);
394  // push back the index of the first SpacePoint (50:50 chance of getting the right one without further testing)
395  lowDistanceInds.push_back(iSp);
396  }
397  oldPosition = position;
398  }
399 
400  return lowDistanceInds;
401 }
402 
403 // ============================================================= REMOVE SPACEPOINTS ===============================================
404 const std::vector<int>
405 SPTCRefereeModule::removeSpacePoints(Belle2::SpacePointTrackCand* trackCand, const std::vector<int>& indsToRemove)
406 {
407  std::vector<int> removedInds; // return vector
408  try {
409  unsigned int nInds = indsToRemove.size();
410  B2DEBUG(20, "Got " << nInds << " indices to remove from SPTC " << trackCand->getArrayIndex());
411 
412  int nRemoved = 0;
413  for (int index : boost::adaptors::reverse(indsToRemove)) { // reverse iteration as trackCand gets 'resized' with every remove
414  B2DEBUG(20, "Removing " << nRemoved + 1 << " from " << nInds << ". index = " << index); // +1 only for better readability
415  trackCand->removeSpacePoint(index);
416  nRemoved++;
418  B2DEBUG(20, "Removed SpacePoint " << index << " from SPTC " << trackCand->getArrayIndex());
419  // NOTE: this way if a removed SpacePoint is "at the edge" between two trackStubs the status will be assigned to the second of those!
420  removedInds.push_back(index - (nInds - nRemoved));
421  }
423  } catch (SpacePointTrackCand::SPTCIndexOutOfBounds& anE) {
424  B2WARNING("Caught an Exception while trying to remove a SpacePoint from a SpacePointTrackCand: " << anE.what());
425  }
426 
427  return removedInds;
428 }
429 // =========================================================== CHECK CURLING ======================================================
430 const std::vector<int> SPTCRefereeModule::checkCurling(Belle2::SpacePointTrackCand* trackCand, bool useMCInfo)
431 {
432  std::vector<int> splitInds; // return vector
433 
434  //catch cases where there are no space points in the trackCand!
435  if (trackCand->getHits().size() == 0) return splitInds;
436 
437  // Only do curling checking if useMCInfo is false, OR if useMCInfo is true if the SPTCs SpacePoints have been checked for a relation to TrueHits!
439 
440  std::string mcInfoStr = useMCInfo ? std::string("with") : std::string("without");
441  B2DEBUG(20, "Checking SpacePointTrackCand " << trackCand->getArrayIndex() << " from Array " << trackCand->getArrayName() <<
442  " for curling behavior " << mcInfoStr << " MC Information");
443 
444  // get the SpacePoints of the TrackCand
445  const std::vector<const SpacePoint*>& tcSpacePoints = trackCand->getHits();
446  B2DEBUG(20, "SPTC has " << tcSpacePoints.size() << " SpacePoints");
447 
448  // get the directions of flight for every SpacePoint
449  const std::vector<bool> dirsOfFlight = getDirectionsOfFlight(tcSpacePoints, useMCInfo);
450 
451  // if(trackCand->getNHits() != dirsOfFlight.size()) B2FATAL("did not get a direction of flight for every SpacePoint"); // should not /cannot happen
452 
453  // loop over all entries of dirsOfFlight and compare them pair-wise. If they change -> add Index to splitInds.
454  if (!dirsOfFlight.at(0)) {
455  // if the direction of flight is inwards for the first hit, push_back 0 -> make information accessible from outside this function
456  splitInds.push_back(0);
457  B2DEBUG(20, "Direction of flight was inwards for first SpacePoint of this SPTC");
458  }
459  // DEBUG output
460  B2DEBUG(20, "Direction of flight is " << dirsOfFlight.at(0) << " for SpacePoint " << 0 << " of this SPTC");
461  for (unsigned int i = 1; i < dirsOfFlight.size(); ++i) {
462  B2DEBUG(20, "Direction of flight is " << dirsOfFlight.at(i) << " for SpacePoint " << i << " of this SPTC");
463  if (dirsOfFlight.at(i) ^ dirsOfFlight.at(i - 1)) {
464  splitInds.push_back(i); // NOTE: using the bitoperator for XOR here to determine if the bools differ!
465  B2DEBUG(20, "Direction of flight has changed from SpacePoint " << i - 1 << " to " << i << ".");
466  }
467  } // END DEBUG output
468  } else {
469  B2ERROR("'useMCInfo' is set to true, but SpacePoints of SPTC have not been checked for relations to TrueHits! Not Checking this SPTC for curling!");
470  trackCand->setTrackStubIndex(-1); // reset to not being checked for curling
471  }
472  return splitInds;
473 }
474 
475 // ============================================================ SPLIT CURLING TRACK CAND ==========================================
476 std::vector<Belle2::SpacePointTrackCand>
477 SPTCRefereeModule::splitTrackCand(const Belle2::SpacePointTrackCand* trackCand, const std::vector<int>& splitIndices,
478  bool onlyFirstPart, const CheckInfo& prevChecksInfo, bool removedHits)
479 {
480  std::vector<SpacePointTrackCand> trackStubs; // return vector
481 
482  B2DEBUG(20, "Splitting SpacePointTrackCand " << trackCand->getArrayIndex() << " from Array " << trackCand->getArrayName() <<
483  ": number of entries in splitIndices " << splitIndices.size());
484  // int trackStub = 0;
485  bool dirOfFlight = splitIndices.at(0) != 0; // if first entry is zero the direction of flight is false (= ingoing)
486 
487  B2DEBUG(20, "first entry of passed vector<int> is " << splitIndices.at(0) << " --> direction of flight is " << dirOfFlight);
488  // if the first entry of splitIndices is zero the first TrackStub is from 0 to second entry instead of from 0 to first entry
489  int firstLast = dirOfFlight ? splitIndices.at(0) : splitIndices.at(1);
490  std::vector<std::pair<int, int> >
491  rangeIndices; // .first is starting, .second is final index for each TrackStub. Store them in vector to be able to easily loop over them
492  rangeIndices.push_back(std::make_pair(0, firstLast));
493 
494  if (!onlyFirstPart) { // if more than the first part is desired push_back the other ranges too
495  unsigned int iStart = dirOfFlight ? 1 : 2;
496  for (unsigned int i = iStart; i < splitIndices.size(); ++i) {
497  rangeIndices.push_back(std::make_pair(splitIndices.at(i - 1), splitIndices.at(i)));
498  }
499  // last TrackStub is from last split index to end of TrackCand
500  rangeIndices.push_back(std::make_pair(splitIndices.at(splitIndices.size() - 1), trackCand->getNHits()));
501  }
502  B2DEBUG(20, "There will be " << rangeIndices.size() << " TrackStubs created for this TrackCand. (size of the passed splitIndices: "
503  << splitIndices.size() << ", onlyFirstPart " << onlyFirstPart);
504 
505  if (LogSystem::Instance().isLevelEnabled(LogConfig::c_Debug, 999, PACKAGENAME())) {
506  stringstream dbOutput;
507  dbOutput << "The indices that will be used for splitting the SPTC: ";
508  for (auto entry : rangeIndices) { dbOutput << "[" << entry.first << "," << entry.second << ") "; }
509  B2DEBUG(20, dbOutput.str());
510  }
511 
512  // loop over all entries in range indices and create a SpacePointTrackCand from it
513  for (unsigned int iTs = 0; iTs < rangeIndices.size(); ++iTs) {
514  int firstInd = rangeIndices.at(iTs).first;
515  int lastInd = rangeIndices.at(iTs).second;
516 
517  unsigned short int refStatus = getCheckStatus(trackCand);
518 
519  B2DEBUG(20, "Trying to create TrackStub from SPTC " << trackCand->getArrayIndex() << " with indices [" << firstInd << "," <<
520  lastInd << ")");
521  // encapsulate in try block to catch indices out of range
522  try {
523  const std::vector<const SpacePoint*> spacePoints = trackCand->getHitsInRange(firstInd, lastInd);
524  const std::vector<double> sortingParams = trackCand->getSortingParametersInRange(firstInd, lastInd);
525 
526  // create new TrackCand
527  SpacePointTrackCand trackStub(spacePoints, trackCand->getPdgCode(), trackCand->getChargeSeed(), trackCand->getMcTrackID());
528  trackStub.setSortingParameters(sortingParams);
529 
530  // set the state seed and the cov seed only for the first trackStub of the TrackCand
531  if (iTs < 1) {
532  trackStub.set6DSeed(trackCand->getStateSeed());
533  trackStub.setCovSeed(trackCand->getCovSeed());
534  }
535 
536  // set the direction of flight and flip it afterwards, because next trackCand hs changed direction of flight
537  trackStub.setFlightDirection(dirOfFlight);
538  dirOfFlight = !dirOfFlight;
539 
540  // trackStub index starts at 1 for curling SPTCs. NOTE: this might be subject to chagnes with the new bitfield in SpacePointTrackCand
541  trackStub.setTrackStubIndex(iTs + 1);
542 
543  // determine and set the referee status of this trackStub based upon the information from the previous tests
544  const std::vector<int>& sameSensInds = std::get<0>(prevChecksInfo);
545  const std::vector<int>& lowDistInds = std::get<0>(prevChecksInfo);
546  bool hasSameSens = vectorHasValueBetween(sameSensInds, rangeIndices.at(iTs));
547  bool hasLowDist = vectorHasValueBetween(lowDistInds, rangeIndices.at(iTs));
548  if ((hasSameSens || hasLowDist) && removedHits) refStatus += SpacePointTrackCand::c_removedHits;
549  if (hasSameSens && !removedHits) refStatus += SpacePointTrackCand::c_hitsOnSameSensor;
550  if (hasLowDist && !removedHits) refStatus += SpacePointTrackCand::c_hitsLowDistance;
551 
552  trackStub.setRefereeStatus(refStatus);
553  B2DEBUG(20, "Set TrackStubIndex " << iTs + 1 << " and refereeStatus " << trackStub.getRefereeStatus() <<
554  " for this trackStub (refStatus string: " << trackStub.getRefereeStatusString());
555 
556  trackStubs.push_back(trackStub);
557  if (LogSystem::Instance().isLevelEnabled(LogConfig::c_Debug, 499, PACKAGENAME())) { trackStub.print(); }
558  } catch (SpacePointTrackCand::SPTCIndexOutOfBounds& anE) {
559  B2WARNING("Caught an exception while trying to split a curling SpacePointTrackCand: " << anE.what() <<
560  " This trackStub will not be created!");
561  }
562  }
563 
564  return trackStubs;
565 }
566 
567 // ========================================================= GET DIRECTIONS OF FLIGHT =============================================
568 const std::vector<bool>
569 SPTCRefereeModule::getDirectionsOfFlight(const std::vector<const Belle2::SpacePoint*>& spacePoints, bool useMCInfo)
570 {
571  std::vector<bool> dirsOfFlight; // return vector
572 
573  if (useMCInfo) {
574  try {
575  for (const SpacePoint* spacePoint : spacePoints) { // loop over all SpacePoints
576  if (spacePoint->getType() == VXD::SensorInfoBase::PXD) {
577  dirsOfFlight.push_back(getDirOfFlightTrueHit<PXDTrueHit>(spacePoint, m_origin));
578  } else if (spacePoint->getType() == VXD::SensorInfoBase::SVD) {
579  dirsOfFlight.push_back(getDirOfFlightTrueHit<SVDTrueHit>(spacePoint, m_origin));
580  } else throw
581  SpacePointTrackCand::UnsupportedDetType(); // NOTE: should never happen, because SpacePointTrackCand can only handle PXD and SVD at the moment!
582  }
583  } catch (SpacePointTrackCand::UnsupportedDetType& anE) {
584  B2FATAL("Caught a fatal exception while checking if a SpacePointTrackCand curls: " <<
585  anE.what()); // FATAL because if this happens this needs some time to implement and it affects more than only this module!
586  }
587  } else {
588  dirsOfFlight = getDirsOfFlightSpacePoints(spacePoints, m_origin);
589  }
590 
591  return dirsOfFlight;
592 }
593 
594 // ================================================ GET DIRECTION OF FLIGHT FROM TRUEHIT ==========================================
595 template <typename TrueHitType>
597 {
598  TrueHitType* trueHit = spacePoint->template getRelatedTo<TrueHitType>("ALL"); // COULDDO: search only certain arrays
599 
600  if (trueHit == nullptr) { B2ERROR("Found no TrueHit to SpacePoint " << spacePoint->getArrayIndex() << " from Array " << spacePoint->getArrayName()); }
601 
602  // get SensorId - needed for transforming local to global coordinates
603  VxdID vxdID = trueHit->getSensorID();
604 
605  const VXD::SensorInfoBase& sensorInfoBase = VXD::GeoCache::getInstance().getSensorInfo(vxdID);
606  B2Vector3F position = sensorInfoBase.pointToGlobal(B2Vector3F(trueHit->getU(), trueHit->getV(), 0), true); // global position
607  B2Vector3F momentum = sensorInfoBase.vectorToGlobal(trueHit->getMomentum(), true); // global momentum
608 
609  B2DEBUG(20, "Getting the direction of flight for SpacePoint " << spacePoint->getArrayIndex() << ", related to TrueHit " <<
610  trueHit->getArrayIndex() << ". Both are on Sensor " << vxdID << ". (TrueHit) Position: (" << position.x() << "," << position.y() <<
611  "," << position.z() << "), (TrueHit) Momentum: (" << momentum.x() << "," << momentum.y() << "," << momentum.z() << ")");
612 
613  return getDirOfFlightPosMom(position, momentum, origin);
614 }
615 
616 // ==================================================== GET DIRECTION OF FLIGHT FROM SPACEPOINT ===================================
617 std::vector<bool>
618 SPTCRefereeModule::getDirsOfFlightSpacePoints(const std::vector<const Belle2::SpacePoint*>& spacePoints, B2Vector3F origin)
619 {
620  std::vector<bool> dirsOfFlight; // return vector
621 
622  B2Vector3F oldPosition = origin; // assumption: first position is origin
623  for (unsigned int iSP = 0; iSP < spacePoints.size(); ++iSP) {
624  B2Vector3F position = spacePoints.at(iSP)->getPosition();
625  // estimate momentum by linearizing between old position and new position -> WARNING: not a very good estimate!!!
626  B2Vector3F momentumEst = position - oldPosition;
627  B2DEBUG(20, "Getting the direction of flight for SpacePoint " << spacePoints.at(iSP)->getArrayIndex() << ". Position: (" <<
628  position.x() << "," << position.y() << "," << position.z() << "), estimated momentum: (" << momentumEst.x() << "," <<
629  momentumEst.y() << "," << momentumEst.z() << ")");
630  dirsOfFlight.push_back(getDirOfFlightPosMom(position, momentumEst, origin));
631  oldPosition = position; // reassign for next round
632  }
633 
634  return dirsOfFlight;
635 }
636 
637 // =============================================== GET DIRECTION OF FLIGHT FROM POSITION AND MOMENTUM =============================
639 {
640  // calculate the positon relative to the set origin, and add the momentum to the position to get the direction of flight
641  B2Vector3F originToHit = position - origin;
642 
643  B2DEBUG(20, "Position relative to origin: (" << originToHit.x() << "," << originToHit.y() << "," << originToHit.z() <<
644  "). Momentum : (" << momentum.x() << "," << momentum.y() << "," <<
645  momentum.z() << ").");
646 
647  // get dot product of momentum and hit position for the perpendicular component only!
648  float dot_xy = originToHit.x() * momentum.x() + originToHit.y() * momentum.y();
649 
650  B2DEBUG(20, "result dot product xy component between postion and momentum: " << dot_xy);
651 
652  if (dot_xy < 0) {
653  B2DEBUG(20, "Direction of flight is inwards for this hit");
654  return false;
655  } else {
656  B2DEBUG(20, "Direction of flight is outwards for this hit");
657  return true;
658  }
659 }
660 
661 // ============================================ COPY TO NEW STORE ARRAY ===========================================================
664 {
665  SpacePointTrackCand* newTC = newStoreArray.appendNew(*trackCand);
666  newTC->addRelationTo(trackCand);
667  B2DEBUG(20, "Added new SPTC to StoreArray " << newStoreArray.getName() << " and registered relation to SPTC " <<
668  trackCand->getArrayIndex() << " from Array " << trackCand->getArrayName());
669 }
670 
671 // =================================================== ADD TO STORE ARRAY =========================================================
674  const Belle2::SpacePointTrackCand* origTrackCand)
675 {
676  SpacePointTrackCand* newTC = storeArray.appendNew(trackCand);
677  newTC->addRelationTo(origTrackCand);
678  B2DEBUG(20, "Added new SPTC to StoreArray " << storeArray.getName() << " and registered relation to SPTC " <<
679  origTrackCand->getArrayIndex() << " from Array " << origTrackCand->getArrayName());
681 }
682 
683 // ======================================================== GET CHECK STATUS ======================================================
685 {
686  unsigned short int status = trackCand->getRefereeStatus();
690  return status;
691 }
DataType Z() const
access variable Z (= .at(2) without boundary check)
Definition: B2Vector3.h:420
DataType y() const
access variable Y (= .at(1) without boundary check)
Definition: B2Vector3.h:412
DataType z() const
access variable Z (= .at(2) without boundary check)
Definition: B2Vector3.h:414
DataType X() const
access variable X (= .at(0) without boundary check)
Definition: B2Vector3.h:416
DataType Y() const
access variable Y (= .at(1) without boundary check)
Definition: B2Vector3.h:418
DataType Mag() const
The magnitude (rho in spherical coordinate system).
Definition: B2Vector3.h:144
DataType x() const
access variable X (= .at(0) without boundary check)
Definition: B2Vector3.h:410
void SetXYZ(DataType x, DataType y, DataType z)
set all coordinates using data type
Definition: B2Vector3.h:445
@ c_DontWriteOut
Object/array should be NOT saved by output modules.
Definition: DataStore.h:71
@ c_ErrorIfAlreadyRegistered
If the object/array was already registered, produce an error (aborting initialisation).
Definition: DataStore.h:72
@ c_Event
Different object in each event, all objects/arrays are invalidated after event() function has been ca...
Definition: DataStore.h:59
@ c_Debug
Debug: for code development.
Definition: LogConfig.h:26
static LogSystem & Instance()
Static method to get a reference to the LogSystem instance.
Definition: LogSystem.cc:31
Base class for Modules.
Definition: Module.h:72
This is the Reconstruction Event-Data Model Track.
Definition: RecoTrack.h:76
Class for type safe access to objects that are referred to in relations.
size_t size() const
Get number of relations.
void addRelationTo(const RelationsInterface< BASE > *object, float weight=1.0, const std::string &namedRelation="") const
Add a relation from this object to another object (with caching).
std::string getArrayName() const
Get name of array this object is stored in, or "" if not found.
int getArrayIndex() const
Returns this object's array index (in StoreArray), or -1 if not found.
RelationVector< TO > getRelationsTo(const std::string &name="", const std::string &namedRelation="") const
Get the relations that point from this object to another store array.
unsigned int m_kickedSpacePointsCtr
counter of kicked SpacePoints
bool m_PARAMkeepOnlyFirstPart
parameter for keeping only the first part of a curling SpacePointTrackCand
std::vector< bool > getDirsOfFlightSpacePoints(const std::vector< const Belle2::SpacePoint * > &spacePoints, B2Vector3F origin)
get the directions of flight for a vector of SpacePoints using only information from SpacePoints (i....
std::string m_curlingArrayName
name of the StoreArray in which the trackStubs from a curling SPTC are stored
const std::vector< int > checkCurling(Belle2::SpacePointTrackCand *trackCand, bool useMCInfo)
Check if the SpacePointTrackCand shows curling behavior.
SPTCRefereeModule()
Constructor.
unsigned int m_regTrackStubsCtr
counter for the number of track stubs that were registered by this module
unsigned int m_SameSensorCtr
counter for TrackCands with SpacePoints on the same sensor
void copyToNewStoreArray(const Belle2::SpacePointTrackCand *trackCand, Belle2::StoreArray< Belle2::SpacePointTrackCand > newStoreArray)
copy the SpacePointTrackCand to a new StoreArray and register a relation to the original trackCand
double m_PARAMminDistance
minimal distance two subsequent SpacePoints have to be seperated
unsigned int m_minDistanceCtr
counter for TrackCands with SpacePoints not far enough apart
const std::vector< int > checkMinDistance(Belle2::SpacePointTrackCand *trackCand, double minDistance)
Check if two subsequent SpacePoints are seperated by at least the provided minDistance.
unsigned short int getCheckStatus(const Belle2::SpacePointTrackCand *trackCand)
get the checked referee status of a SPTC (i.e.
std::vector< double > m_PARAMsetOrigin
assumed interaction point from which the SpacePointTrackCands emerge.
void event() override
event: check SpacePointTrackCands
bool getDirOfFlightTrueHit(const Belle2::SpacePoint *spacePoint, B2Vector3F origin)
get the direction of flight for a SpacePoint by using information from the underlying TrueHit NOTE: t...
void terminate() override
terminate: print some summary information
std::tuple< std::vector< int >, std::vector< int > > CheckInfo
typedef for storing the outcome of previously done checks to have them available later.
unsigned int m_totalTrackCandCtr
counter for the total number of TrackCands
std::string m_PARAMsptcName
Name of input container of SpacePointTrackCands.
B2Vector3F m_origin
origin used internally.
std::vector< Belle2::SpacePointTrackCand > splitTrackCand(const Belle2::SpacePointTrackCand *trackCand, const std::vector< int > &splitIndices, bool onlyFirstPart, const CheckInfo &prevChecksInfo, bool removedHits)
split a curling SpacePointTrackCand into TrackStubs.
int m_PARAMminNumSpacePoints
only keep track candidates which have at least m_PARAMminNumSpacePoints space points
bool getDirOfFlightPosMom(B2Vector3F position, B2Vector3F momentum, B2Vector3F origin)
get the direction of flight provided the global position and momentum of a SpacePoint/TrueHit for the...
unsigned int m_allInwardsCtr
counter for the number of SPTCs which have direction of flight inward for all SpacePoints in them
bool m_PARAMkickSpacePoint
parameter for indicating if only the 'problematic' SpacePoint shall be removed from the SPTC or if th...
bool m_PARAMstoreNewArray
parameter for indicating if all checked SpacePointTrackCands should be stored in a new StoreArray NOT...
unsigned int m_curlingTracksCtr
counter for tracks that curl
void addToStoreArray(const Belle2::SpacePointTrackCand &trackCand, Belle2::StoreArray< Belle2::SpacePointTrackCand > storeArray, const Belle2::SpacePointTrackCand *origTrackCand)
register the SpacePointTrackCand (i.e.
bool vectorHasValueBetween(std::vector< T > V, std::pair< T, T > P)
function to determine if any of the values in vector V are between the values of P (i....
const std::vector< int > removeSpacePoints(Belle2::SpacePointTrackCand *trackCand, const std::vector< int > &indsToRemove)
remove the SpacePoint passed to this function from the SpacePointTrackCand
bool m_PARAMcheckSameSensor
parameter for indicating if the check for subsequent SpacePoints being on the same sensor should be d...
bool m_PARAMcheckMinDistance
parameter for indicating if the check for the minimal distance between two subsequent SpacePoints sho...
std::string m_PARAMcurlingSuffix
Suffix that will be used to get a name for the StoreArray that holds the trackStubs that were obtaine...
std::string m_PARAMnewArrayName
Name of the output container of SpacePointTrackCands if 'storeNewArray' is set to true.
const std::vector< int > checkSameSensor(Belle2::SpacePointTrackCand *trackCand)
Check if two subsequent SpacePoints are on the same sensor.
void initializeCounters()
initialize all counters to 0
bool m_PARAMuseMCInfo
parameter for indicating if MC information should be used or not
const std::vector< bool > getDirectionsOfFlight(const std::vector< const Belle2::SpacePoint * > &spacePoints, bool useMCInfo)
get the directions of Flight for every SpacePoint in the passed vector.
bool m_PARAMcheckIfFitted
if true it is looked for any related RecoTrack and if that RecoTrack has a valid fit.
bool m_PARAMsplitCurlers
parameter for switching on/off the splitting of curling SpacePointTrackCands
bool m_PARAMcheckCurling
parameter for indicating if the SpacePointTrackCand should be checked for curling
Storage for (VXD) SpacePoint-based track candidates.
void setSortingParameters(const std::vector< double > &sortParams)
set the sorting parameters
void set6DSeed(const TVectorD &state6D)
set the 6D state seed
unsigned int getNHits() const
get the number of hits (space points) in the track candidate
int getPdgCode() const
get pdg code
void removeSpacePoint(int indexInTrackCand)
remove a SpacePoint (and its sorting parameter) from the SpacePointTrackCand
unsigned short int getRefereeStatus(unsigned short int bitmask=USHRT_MAX) const
Return the refere status code of the SpacePointTrackCand.
void setCovSeed(const TMatrixDSym &cov)
set the covariance matrix seed
int getMcTrackID() const
get the MC Track ID
const std::vector< const Belle2::SpacePoint * > & getHits() const
get hits (space points) of track candidate
@ c_curlingTrack
bit 8: SPTC is curling (resp.
@ c_checkedTrueHits
bit 5: All SpacePoints of the SPTC have a relation to at least one TrueHit.
@ c_removedHits
bit 4: SpacePoints were removed from this SPTC.
@ c_hitsLowDistance
bit 3: SPTC has two (or more) SpacePoints that are not far enough apart.
@ c_checkedClean
bit 1: SPTC shows no 'problematic' behaviour.
@ c_checkedMinDistance
bit 7: It has been checked if two consecutive SpacePoints are far enough apart.
@ c_hasFittedRecoTrack
bit 13: SPTC is related to a RecoTrack which has a successful fit.
@ c_checkedSameSensors
bit 6: It has been checked, if two consecutive SpacePoints are on the same sensor for this SPTC.
@ c_checkedByReferee
bit 0: SPTC has been checked by a Referee (all possible tests).
@ c_hitsOnSameSensor
bit 2: SPTC has two (or more) SpacePoints on same sensor.
bool isCurling() const
get if the TrackCand is curling.
void setRefereeStatus(unsigned short int bitmask)
set referee status (resets the complete to the passed status!)
void setTrackStubIndex(int trackStubInd)
set TrackStub index
void print(int debuglevel=150, const Option_t *="") const
print the Track Candidate in its "full beauty".
const TMatrixDSym & getCovSeed() const
get the covariance matrix seed (6D).
const std::vector< const Belle2::SpacePoint * > getHitsInRange(int firstInd, int lastInd) const
get hits (SpacePoints) in range (indices of SpacePoint inside SpacePointTrackCand) including first in...
bool hasRefereeStatus(unsigned int short bitmask) const
Check if the SpacePointTrackCand has the status characterized by the bitmask.
const std::vector< double > getSortingParametersInRange(int firstIndex, int lastIndex) const
get the sorting parameters in range (indices of SpacePoints inside SpacePointTrackCand) including fir...
const TVectorD & getStateSeed() const
get state seed as 6D vector
std::string getRefereeStatusString(std::string delimiter=" ") const
get the refereeStatus as a string (easier to read than an unsigned short int)
double getChargeSeed() const
get charge
void setFlightDirection(bool direction)
set the direction of flight (true is outgoing, false is ingoing).
void addRefereeStatus(unsigned short int bitmask)
add a referee status
SpacePoint typically is build from 1 PXDCluster or 1-2 SVDClusters.
Definition: SpacePoint.h:42
bool isRequired(const std::string &name="")
Ensure this array/object has been registered previously.
const std::string & getName() const
Return name under which the object is saved in the DataStore.
bool registerInDataStore(DataStore::EStoreFlags storeFlags=DataStore::c_WriteOut)
Register the object/array in the DataStore.
T * appendNew()
Construct a new T object at the end of the array.
Definition: StoreArray.h:246
int getEntries() const
Get the number of objects in the array.
Definition: StoreArray.h:216
bool registerRelationTo(const StoreArray< TO > &toArray, DataStore::EDurability durability=DataStore::c_Event, DataStore::EStoreFlags storeFlags=DataStore::c_WriteOut, const std::string &namedRelation="") const
Register a relation to the given StoreArray.
Definition: StoreArray.h:140
Type-safe access to single objects in the data store.
Definition: StoreObjPtr.h:95
const SensorInfoBase & getSensorInfo(Belle2::VxdID id) const
Return a referecne to the SensorInfo of a given SensorID.
Definition: GeoCache.cc:66
static GeoCache & getInstance()
Return a reference to the singleton instance.
Definition: GeoCache.cc:213
Base class to provide Sensor Information for PXD and SVD.
TVector3 pointToGlobal(const TVector3 &local, bool reco=false) const
Convert a point from local to global coordinates.
TVector3 vectorToGlobal(const TVector3 &local, bool reco=false) const
Convert a vector from local to global coordinates.
Class to uniquely identify a any structure of the PXD and SVD.
Definition: VxdID.h:33
B2Vector3< float > B2Vector3F
typedef for common usage with float
Definition: B2Vector3.h:496
#define REG_MODULE(moduleName)
Register the given module (without 'Module' suffix) with the framework.
Definition: Module.h:650
DataType at(unsigned i) const
safe member access (with boundary check!)
Definition: B2Vector3.h:650
Abstract base class for different kinds of events.