Belle II Software development
TOPBunchFinderModule.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// Own header.
10#include <top/modules/TOPBunchFinder/TOPBunchFinderModule.h>
11
12// TOP headers.
13#include <top/geometry/TOPGeometryPar.h>
14#include <top/reconstruction_cpp/TOPTrack.h>
15#include <top/reconstruction_cpp/PDFConstructor.h>
16#include <top/reconstruction_cpp/TOPRecoManager.h>
17#include <top/reconstruction_cpp/PDF1Dim.h>
18#include <top/utilities/Chi2MinimumFinder1D.h>
19
20// Dataobject classes
21#include <mdst/dataobjects/TrackFitResult.h>
22#include <mdst/dataobjects/HitPatternCDC.h>
23#include <tracking/dataobjects/ExtHit.h>
24#include <mdst/dataobjects/MCParticle.h>
25#include <top/dataobjects/TOPBarHit.h>
26#include <cdc/dataobjects/CDCDedxLikelihood.h>
27#include <reconstruction/dataobjects/VXDDedxLikelihood.h>
28#include <mdst/dataobjects/PIDLikelihood.h>
29
30// framework aux
31#include <framework/logging/Logger.h>
32
33using namespace std;
34
35namespace Belle2 {
40 using namespace TOP;
41
42 //-----------------------------------------------------------------
44 //-----------------------------------------------------------------
45
46 REG_MODULE(TOPBunchFinder);
47
48 //-----------------------------------------------------------------
49 // Implementation
50 //-----------------------------------------------------------------
51
53 {
54 // set module description (e.g. insert text)
55 setDescription("A precise event T0 determination w.r.t local time reference of TOP counter. "
56 "Results available in TOPRecBunch.");
58
59 // Add parameters
60 addParam("numBins", m_numBins, "number of bins of fine search region", 200);
61 addParam("timeRangeFine", m_timeRangeFine,
62 "time range in which to do fine search [ns]", 10.0);
63 addParam("timeRangeCoarse", m_timeRangeCoarse,
64 "time range in which to do coarse search, if autoRange turned off [ns]", 100.0);
65 addParam("autoRange", m_autoRange,
66 "turn on/off automatic determination of the coarse search region (false means off)", false);
67 addParam("sigmaSmear", m_sigmaSmear,
68 "sigma in [ns] for additional smearing of PDF", 0.0);
69 addParam("minSignal", m_minSignal,
70 "minimal number of signal photons to accept track", 8.0);
71 addParam("minSBRatio", m_minSBRatio,
72 "minimal signal-to-background ratio to accept track", 0.0);
73 addParam("minDERatio", m_minDERatio,
74 "minimal ratio of detected-to-expected photons to accept track", 0.2);
75 addParam("maxDERatio", m_maxDERatio,
76 "maximal ratio of detected-to-expected photons to accept track", 2.5);
77 addParam("minPt", m_minPt, "minimal p_T of the track", 0.3);
78 addParam("maxPt", m_maxPt, "maximal p_T of the track", 6.0);
79 addParam("maxD0", m_maxD0, "maximal absolute value of helix perigee distance", 2.0);
80 addParam("maxZ0", m_maxZ0, "maximal absolute value of helix perigee z coordinate", 4.0);
81 addParam("minNHitsCDC", m_minNHitsCDC, "minimal number of hits in CDC", 20);
82 addParam("useMCTruth", m_useMCTruth,
83 "if true, use MC truth for particle mass instead of the most probable from dEdx",
84 false);
85 addParam("saveHistograms", m_saveHistograms,
86 "if true, save histograms to TOPRecBunch and TOPTimeZeros", false);
87 addParam("tau", m_tau,
88 "first order filter time constant [number of events]", 100.0);
89 addParam("correctDigits", m_correctDigits,
90 "if true, subtract bunch time in TOPDigits", true);
91 addParam("subtractRunningOffset", m_subtractRunningOffset,
92 "if true and correctDigits = True, subtract running offset in TOPDigits "
93 "when running in HLT mode. It must be set to false when running calibration.",
94 true);
95 addParam("bunchesPerSSTclk", m_bunchesPerSSTclk,
96 "number of bunches per SST clock period", 24);
97 addParam("usePIDLikelihoods", m_usePIDLikelihoods,
98 "use PIDLikelihoods instead of DedxLikelihoods (only if run on cdst files)",
99 false);
100 addParam("nTrackLimit", m_nTrackLimit,
101 "maximum number of tracks (inclusive) to use three particle hypotheses in fine search "
102 "(only when running in data processing mode).", unsigned(3));
103 addParam("useTimeSeed", m_useTimeSeed, "use SVD or CDC event T0 as a seed "
104 "(only when running in data processing mode and autoRange turned off).", true);
105 addParam("useFillPattern", m_useFillPattern, "use known accelerator fill pattern to enhance efficiency "
106 "(only when running in data processing mode).", true);
107 }
108
109
111 {
112 // input collections
113
114 m_topDigits.isRequired();
115 m_topRawDigits.isOptional();
116 m_tracks.isRequired();
117 StoreArray<ExtHit> extHits;
118 extHits.isRequired();
119 m_initialParticles.isOptional();
120
121 if (m_useMCTruth) {
122 StoreArray<MCParticle> mcParticles;
123 mcParticles.isRequired();
124 StoreArray<TOPBarHit> barHits;
125 barHits.isRequired();
126 } else {
128 StoreArray<PIDLikelihood> pidLikelihoods;
129 pidLikelihoods.isRequired();
130 } else {
131 StoreArray<CDCDedxLikelihood> cdcDedxLikelihoods;
132 cdcDedxLikelihoods.isRequired();
133 StoreArray<VXDDedxLikelihood> vxdDedxLikelihoods;
134 vxdDedxLikelihoods.isOptional();
135 }
136 }
137
138 // output
139
140 m_recBunch.registerInDataStore();
141 m_timeZeros.registerInDataStore();
142 m_timeZeros.registerRelationTo(extHits);
143 m_eventT0.registerInDataStore(); // usually it is already registered in tracking
144
145 // bunch separation in time
146
147 const auto* geo = TOPGeometryPar::Instance()->getGeometry();
148 m_bunchTimeSep = geo->getNominalTDC().getSyncTimeBase() / m_bunchesPerSSTclk;
149
150 // prior probabilities: from generic BBbar simulation
151 // - MCParticles with reconstructed track and at least 5 detected Cherenkov photons
152
153 m_priors[11] = 0.062; // electrons
154 m_priors[13] = 0.086; // muons
155 m_priors[211] = 0.734; // pions
156 m_priors[321] = 0.106; // kaons
157 m_priors[2212] = 0.013; // protons
158 m_priors[1000010020] = 0; // deuterons
159
160 double s = 0;
161 for (const auto& prior : m_priors) s += prior.second;
162 for (auto& prior : m_priors) prior.second /= s;
163
164 if (not m_commonT0.isValid()) {
165 B2ERROR("Common T0 calibration payload requested but not available");
166 return;
167 }
168
169 /*************************************************************************
170 * auto detection of HLT/express reco mode via status of common T0 payload:
171 * c_Default -> HLT/express reco mode
172 * c_Calibrated -> data processing mode
173 * c_Unusable -> HLT/express reco mode
174 * c_roughlyCalibrated -> HLT/express reco mode
175 *************************************************************************/
176
177 if (m_commonT0->isCalibrated()) {
178 m_HLTmode = false;
179 m_runningOffset = 0; // since digits are already commonT0 calibrated
180 m_runningError = m_commonT0->getT0Error();
181 } else if (m_commonT0->isRoughlyCalibrated()) {
182 m_HLTmode = true;
183 m_runningOffset = m_commonT0->getT0(); // since digits are not commonT0 calibrated
184 m_runningError = m_commonT0->getT0Error();
185 } else {
186 m_HLTmode = true;
187 m_runningOffset = 0;
189 }
190
191 if (m_HLTmode) {
192 m_nTrackLimit = 0; // use single particle hypothesis to save execution time
193 B2INFO("TOPBunchFinder: running in HLT/express reco mode");
194 } else {
195 B2INFO("TOPBunchFinder: running in data processing mode");
196 }
197
198 }
199
200
202 {
203 StoreObjPtr<EventMetaData> evtMetaData;
204
205 if (not m_commonT0.isValid()) {
206 B2FATAL("Common T0 calibration payload requested but not available for run "
207 << evtMetaData->getRun()
208 << " of experiment " << evtMetaData->getExperiment());
209 }
210
211 if (m_HLTmode) return;
212
213 if (m_useTimeSeed and not m_eventT0Offset.isValid()) {
214 B2WARNING("EventT0Offset not available for run "
215 << evtMetaData->getRun()
216 << " of experiment " << evtMetaData->getExperiment()
217 << ": seeding with SVD or CDC eventT0 will not be done.");
218 }
219 if (m_useFillPattern) {
220 if (not m_bunchStructure->isSet()) {
221 B2WARNING("BunchStructure not available for run "
222 << evtMetaData->getRun()
223 << " of experiment " << evtMetaData->getExperiment()
224 << ": fill pattern will not be used.");
225 }
226 if (not m_fillPatternOffset.isValid()) {
227 B2WARNING("FillPatternOffset not available for run "
228 << evtMetaData->getRun()
229 << " of experiment " << evtMetaData->getExperiment()
230 << ": fill pattern will not be used.");
231 }
232 }
233
234 }
235
236
238 {
239
240 m_processed++;
242
243 // define output for the reconstructed bunch
244
245 if (not m_recBunch.isValid()) {
246 m_recBunch.create();
247 } else {
248 m_revo9Counter = m_recBunch->getRevo9Counter();
249 m_recBunch->clearReconstructed();
250 }
251 m_timeZeros.clear();
252
253 if (not m_eventT0.isValid()) m_eventT0.create();
254
255 // set MC truth if available
256
257 if (m_initialParticles.isValid()) {
258 double simTime = m_initialParticles->getTime();
259 int simBunchNumber = round(simTime / m_bunchTimeSep);
260 m_recBunch->setSimulated(simBunchNumber, simTime);
261 }
262 m_isMC = m_recBunch->isSimulated();
263
264 // set revo9 counter from the first raw digit if available (all should be the same)
265
266 if (m_topRawDigits.getEntries() > 0) {
267 const auto* rawDigit = m_topRawDigits[0];
268 m_revo9Counter = rawDigit->getRevo9Counter();
269 m_recBunch->setRevo9Counter(m_revo9Counter);
270 }
271
272 // full time window in which data are taken (smaller time window is used in reconstruction)
273
274 const auto& tdc = TOPGeometryPar::Instance()->getGeometry()->getNominalTDC();
275 double timeWindow = m_feSetting->getReadoutWindows() * tdc.getSyncTimeBase() / static_cast<double>(TOPNominalTDC::c_syncWindows);
276
277 // counters and temporary containers
278
279 int numTrk = 0;
280 m_nodEdxCount = 0;
281 std::vector<TOPTrack> topTracks;
282 std::vector<PDFConstructor> pdfConstructors;
283 std::vector<PDF1Dim> top1Dpdfs;
284 std::vector<int> numPhotons;
285 std::vector<double> assumedMasses;
286 std::vector<Chi2MinimumFinder1D> finders;
287
288 // loop over reconstructed tracks, make a selection and push to containers
289
290 for (const auto& track : m_tracks) {
291 TOPTrack trk(track);
292 if (not trk.isValid()) continue;
293
294 // track selection
295 const auto* fitResult = track.getTrackFitResultWithClosestMass(Const::pion);
296 if (not fitResult) {
297 B2ERROR("No TrackFitResult available. Must be a bug somewhere.");
298 continue;
299 }
300 if (fitResult->getHitPatternCDC().getNHits() < m_minNHitsCDC) continue;
301 if (fabs(fitResult->getD0()) > m_maxD0) continue;
302 if (fabs(fitResult->getZ0()) > m_maxZ0) continue;
303 auto pt = fitResult->getTransverseMomentum();
304 if (pt < m_minPt or pt > m_maxPt) continue;
305
306 // determine most probable particle mass
307 auto chargedStable = Const::pion;
308 if (m_useMCTruth) {
309 if (not trk.getMCParticle()) continue;
310 if (not trk.getBarHit()) continue;
311 chargedStable = Const::chargedStableSet.find(abs(trk.getMCParticle()->getPDG()));
312 if (chargedStable == Const::invalidParticle) continue;
313 } else {
314 if (trk.getMomentumMag() < 4.0) chargedStable = getMostProbable(track);
315 }
316
317 // construct PDF
318 PDFConstructor pdfConstructor(trk, chargedStable, PDFConstructor::c_Rough);
319 if (not pdfConstructor.isValid()) continue;
320 numTrk++;
321
322 // make PDF projection to time axis with bin size of ~0.5 ns
323 PDF1Dim pdf1d(pdfConstructor, 0.5, timeWindow);
324 pdfConstructor.switchOffDeltaRayPDF(); // to speed-up fine search
325
326 // do further track selection
327 double expSignal = pdf1d.getExpectedSignal();
328 double expDelta = pdf1d.getExpectedDeltaPhotons();
329 double expBG = pdf1d.getExpectedBG();
330 double expPhot = expSignal + expDelta + expBG;
331 double numPhot = pdf1d.getNumOfPhotons();
332 if (expSignal < m_minSignal) continue;
333 if (expSignal < m_minSBRatio * expBG) continue;
334 if (numPhot < m_minDERatio * expPhot) continue;
335 if (numPhot > m_maxDERatio * expPhot) continue;
336
337 topTracks.push_back(trk);
338 pdfConstructors.push_back(pdfConstructor);
339 top1Dpdfs.push_back(pdf1d);
340 numPhotons.push_back(numPhot);
341 assumedMasses.push_back(pdfConstructors.back().getHypothesis().getMass());
342 }
343 m_recBunch->setNumTracks(numTrk, topTracks.size(), m_nodEdxCount);
344 if (topTracks.empty()) return;
345
346 // get time seed
347
348 auto timeSeed = getTimeSeed();
349
350 if (timeSeed.sigma == 0) { // time seed is not given - perform coarse search
351
352 // set time region for coarse search
353
354 double minT0 = -m_timeRangeCoarse / 2;
355 double maxT0 = m_timeRangeCoarse / 2;
356 if (m_autoRange) {
357 minT0 = top1Dpdfs[0].getMinT0();
358 maxT0 = top1Dpdfs[0].getMaxT0();
359 for (const auto& pdf : top1Dpdfs) {
360 minT0 = std::min(minT0, pdf.getMinT0());
361 maxT0 = std::max(maxT0, pdf.getMaxT0());
362 }
363 }
364 double binSize = top1Dpdfs[0].getBinSize();
365 int numBins = (maxT0 - minT0) / binSize;
366 maxT0 = minT0 + binSize * numBins;
367
368 // find coarse T0
369
370 for (const auto& pdf : top1Dpdfs) {
371 finders.push_back(Chi2MinimumFinder1D(numBins, minT0, maxT0));
372 auto& finder = finders.back();
373 const auto& bins = finder.getBinCenters();
374 for (unsigned i = 0; i < bins.size(); i++) {
375 double t0 = bins[i];
376 finder.add(i, -2 * pdf.getLogL(t0));
377 }
378 }
379 auto coarseFinder = finders[0];
380 for (size_t i = 1; i < finders.size(); i++) {
381 coarseFinder.add(finders[i]);
382 }
383
384 const auto& t0Coarse = coarseFinder.getMinimum();
385 if (m_saveHistograms) {
386 m_recBunch->addHistogram(coarseFinder.getHistogram("chi2_coarse_",
387 "coarse T0; t_{0} [ns]; -2 log L"));
388 }
389 if (t0Coarse.position < minT0 or t0Coarse.position > maxT0 or not t0Coarse.valid) {
390 B2DEBUG(20, "Coarse T0 finder: returning invalid or out of range T0");
391 return;
392 }
393 timeSeed.t0 = t0Coarse.position;
394 }
395
396 // find precise T0
397
398 finders.clear();
399
400 double timeMin = TOPRecoManager::getMinTime() + timeSeed.t0;
401 double timeMax = TOPRecoManager::getMaxTime() + timeSeed.t0;
402 double timeRangeFine = std::max(m_timeRangeFine, timeSeed.sigma * 6);
403 double t0min = timeSeed.t0 - timeRangeFine / 2;
404 double t0max = timeSeed.t0 + timeRangeFine / 2;
405
406 for (size_t itrk = 0; itrk < topTracks.size(); itrk++) {
407 finders.push_back(Chi2MinimumFinder1D(m_numBins, t0min, t0max));
408 const auto& reco = pdfConstructors[itrk];
409 numPhotons[itrk] = setFinder(finders.back(), reco, timeMin, timeMax);
410 const auto& trk = topTracks[itrk];
411 double momentum = trk.getMomentumMag();
412 if (not m_useMCTruth and momentum > 0.7 and topTracks.size() <= m_nTrackLimit) {
413 std::vector<Const::ChargedStable> other;
414 if (reco.getHypothesis() == Const::kaon) {
415 other.push_back(Const::pion);
416 if (momentum < 4.0) other.push_back(Const::proton);
417 } else if (reco.getHypothesis() == Const::proton) {
418 other.push_back(Const::pion);
419 if (momentum < 2.0) other.push_back(Const::kaon);
420 } else {
421 if (momentum < 2.0) other.push_back(Const::kaon);
422 if (momentum < 4.0) other.push_back(Const::proton);
423 }
424 for (const auto& chargedStable : other) {
425 PDFConstructor pdfConstructor(trk, chargedStable, PDFConstructor::c_Rough);
426 if (not pdfConstructor.isValid()) continue;
427 pdfConstructor.switchOffDeltaRayPDF(); // to speed-up fine search
428 if (pdfConstructor.getExpectedSignalPhotons() < m_minSignal) continue;
429 Chi2MinimumFinder1D finder(m_numBins, t0min, t0max);
430 int numPhot = setFinder(finder, pdfConstructor, timeMin, timeMax);
431 if (numPhot != numPhotons[itrk])
432 B2ERROR("Different number of photons used for log likelihood of different mass hypotheses");
433 if (finder.getMinChi2() < finders.back().getMinChi2()) {
434 finders.back() = finder;
435 assumedMasses[itrk] = chargedStable.getMass();
436 }
437 }
438 }
439 }
440
441 if (finders.size() == 0) return; // just in case
442 auto finderSum = finders[0];
443 for (size_t i = 1; i < finders.size(); i++) {
444 finderSum.add(finders[i]);
445 }
446
447 if (timeSeed.sigma > 0) {
448 const auto& binCenters = finderSum.getBinCenters();
449 for (unsigned i = 0; i < binCenters.size(); i++) {
450 double t0 = binCenters[i];
451 finderSum.add(i, pow((t0 - timeSeed.t0) / timeSeed.sigma, 2)); // add chi2 according to timeSeed resolution
452 }
453 }
454
455 const auto& T0 = finderSum.getMinimum();
456 if (m_saveHistograms) {
457 m_recBunch->addHistogram(finderSum.getHistogram("chi2_fine_", "precise T0; t_{0} [ns]; -2 log L"));
458 }
459 if (T0.position < t0min or T0.position > t0max or not T0.valid) {
460 B2DEBUG(20, "Fine T0 finder: returning invalid or out of range T0");
461 return;
462 }
463
464 // bunch time and current offset
465
466 int bunchNo = lround(T0.position / m_bunchTimeSep); // round to nearest integer
467 double offset = T0.position - m_bunchTimeSep * bunchNo;
468 if (not m_commonT0->isCalibrated()) { // auto set offset range
469 double deltaOffset = offset - m_runningOffset;
470 if (fabs(deltaOffset + m_bunchTimeSep) < fabs(deltaOffset)) {
471 offset += m_bunchTimeSep;
472 bunchNo--;
473 } else if (fabs(deltaOffset - m_bunchTimeSep) < fabs(deltaOffset)) {
474 offset -= m_bunchTimeSep;
475 bunchNo++;
476 }
477 }
478 double error = T0.error;
479
480 // averaging with first order filter (with adoptable time constant)
481
482 double tau = 10 + m_success / 2; // empirically with toy MC
483 if (tau > m_tau) tau = m_tau;
484 double a = exp(-1.0 / tau);
485 m_runningOffset = a * m_runningOffset + (1 - a) * offset;
486 double err1 = a * m_runningError;
487 double err2 = (1 - a) * error;
488 m_runningError = sqrt(err1 * err1 + err2 * err2);
489
490 // when not running in HLT mode, check if reconstructed bunch is filled
491
492 if (not m_HLTmode) {
493 bool isFilled = isBucketFilled(bunchNo); // stores in addition the bucket number and fill status in m_recBunch
494 if (m_useFillPattern and not isFilled) return;
495 }
496
497 // store the results
498
499 double bunchTime = bunchNo * m_bunchTimeSep;
500 m_recBunch->setReconstructed(bunchNo, bunchTime, offset, error, m_runningOffset, m_runningError, timeSeed.detector);
501 m_recBunch->setMinChi2(T0.chi2);
502 double svdOffset = m_eventT0Offset.isValid() and not m_isMC ? m_eventT0Offset->get(Const::SVD).offset : 0;
503 m_eventT0->addTemporaryEventT0(EventT0::EventT0Component(bunchTime + svdOffset, error, Const::TOP, "bunchFinder"));
504 m_success++;
505
506 // store T0 of single tracks relative to bunchTime
507
508 if (finders.size() == topTracks.size()) {
509 for (size_t itrk = 0; itrk < topTracks.size(); itrk++) {
510 const auto& trk = topTracks[itrk];
511 auto& finder = finders[itrk];
512 const auto& t0trk = finder.getMinimum();
513 auto* timeZero = m_timeZeros.appendNew(trk.getModuleID(),
514 t0trk.position - bunchTime,
515 t0trk.error, numPhotons[itrk]);
516 timeZero->setAssumedMass(assumedMasses[itrk]);
517 if (not t0trk.valid) timeZero->setInvalid();
518 timeZero->setMinChi2(finder.getMinChi2());
519 timeZero->addRelationTo(trk.getExtHit());
520
521 if (m_saveHistograms) {
522 std::string num = std::to_string(itrk);
523 auto chi2 = finder.getHistogram("chi2_" + num,
524 "precise T0 single track; t_{0} [ns]; -2 log L");
525 auto pdf = top1Dpdfs[itrk].getHistogram("pdf1D_" + num,
526 "PDF projected to time axis; time [ns]");
527 TH1F hits(("hits_" + num).c_str(),
528 "time distribution of hits (t0-subtracted); time [ns]",
529 pdf.GetNbinsX(), pdf.GetXaxis()->GetXmin(), pdf.GetXaxis()->GetXmax());
530 for (const auto& hit : trk.getSelectedHits()) {
531 hits.Fill(hit.time - t0trk.position);
532 }
533 timeZero->setHistograms(chi2, pdf, hits);
534 }
535 }
536 }
537
538 // correct time in TOPDigits
539
540 if (m_correctDigits) {
541 for (auto& digit : m_topDigits) {
542 digit.subtractT0(bunchTime);
543 digit.addStatus(TOPDigit::c_EventT0Subtracted);
545 digit.subtractT0(m_runningOffset);
546 double err = digit.getTimeError();
547 digit.setTimeError(sqrt(err * err + m_runningError * m_runningError));
548 digit.addStatus(TOPDigit::c_BunchOffsetSubtracted);
549 }
550 }
551 }
552
553 }
554
555
557 {
558 B2RESULT("TOPBunchFinder: event T0 determined for " << m_success << "/"
559 << m_processed << " events");
560 }
561
562
564 {
565
566 std::vector<double> logL;
567 std::vector<double> priors;
568
570 const auto* pid = track.getRelated<PIDLikelihood>();
571 if (not pid) {
573 return Const::pion;
574 }
575 auto subset = Const::PIDDetectorSet(Const::SVD);
576 subset += Const::PIDDetectorSet(Const::CDC);
577 for (const auto& type : Const::chargedStableSet) {
578 logL.push_back(pid->getLogL(type, subset));
579 priors.push_back(m_priors[abs(type.getPDGCode())]);
580 }
581 } else {
582 const auto* cdcdedx = track.getRelated<CDCDedxLikelihood>();
583 const auto* vxddedx = track.getRelated<VXDDedxLikelihood>();
584 if (not cdcdedx and not vxddedx) {
586 return Const::pion;
587 }
588 for (const auto& type : Const::chargedStableSet) {
589 if (cdcdedx and vxddedx) {
590 logL.push_back(cdcdedx->getLogL(type) + vxddedx->getLogL(type));
591 } else if (cdcdedx) {
592 logL.push_back(cdcdedx->getLogL(type));
593 } else {
594 logL.push_back(vxddedx->getLogL(type));
595 }
596 priors.push_back(m_priors[abs(type.getPDGCode())]);
597 }
598 }
599
600 // get maximal logL
601 auto logL_max = logL[0];
602 for (auto x : logL) {
603 if (x > logL_max) logL_max = x;
604 }
605
606 // calculate probabilities, normalizaton is not needed
607 std::vector<double> probability(logL.size());
608 for (unsigned i = 0; i < logL.size(); ++i) {
609 probability[i] = exp(logL[i] - logL_max) * priors[i];
610 }
611
612 // find most probable
613 unsigned i0 = 0;
614 for (unsigned i = 0; i < probability.size(); ++i) {
615 if (probability[i] > probability[i0]) i0 = i;
616 }
617 return Const::chargedStableSet.at(i0);
618
619 }
620
621
622 int TOPBunchFinderModule::setFinder(Chi2MinimumFinder1D& finder, const PDFConstructor& reco, double timeMin, double timeMax)
623 {
624 const auto& binCenters = finder.getBinCenters();
625 int numPhotons = 0;
626 bool sameNumPhotons = true; // for control only
627 double logL_bkg = reco.getBackgroundLogL(timeMin, timeMax).logL;
628 for (unsigned i = 0; i < binCenters.size(); i++) {
629 double t0 = binCenters[i];
630 auto LL = reco.getLogL(t0, timeMin, timeMax, m_sigmaSmear);
631 finder.add(i, -2 * (LL.logL - logL_bkg));
632 if (i == 0) numPhotons = LL.numPhotons;
633 else if (static_cast<int>(LL.numPhotons) != numPhotons) sameNumPhotons = false;
634 }
635
636 if (not sameNumPhotons) B2ERROR("Different number of photons used for log likelihood of different time shifts");
637
638 return numPhotons;
639 }
640
641
643 {
644 TimeSeed timeSeed; // default time seed; sigma == 0 signals that the seed is not given
645
646 if (m_HLTmode) return timeSeed;
647 if (m_autoRange) return timeSeed;
648 if (not m_useTimeSeed) return timeSeed;
649 if (not m_eventT0Offset.isValid()) return timeSeed;
650
651 for (auto detector : {Const::SVD, Const::CDC}) {
652 if (m_eventT0Offset->isAvailable(detector) and m_eventT0->hasTemporaryEventT0(detector)) {
653 auto eventT0s = m_eventT0->getTemporaryEventT0s(detector);
654 if (eventT0s.empty()) continue;
655 if (detector == Const::CDC and eventT0s.back().algorithm != "chi2") continue;
656 double t0 = eventT0s.back().eventT0;
657 if (std::abs(t0) > m_timeRangeCoarse / 2) continue;
658 timeSeed.t0 = m_isMC ? t0 : t0 - m_eventT0Offset->get(detector).offset;
659 timeSeed.sigma = m_eventT0Offset->get(detector).sigma;
660 timeSeed.detector = detector;
661 break;
662 }
663 }
664
665 return timeSeed;
666 }
667
668
670 {
671 // return true if needed information is not available or fill pattern offset is not calibrated
672
673 if (not m_bunchStructure->isSet()) return true;
674 if (m_revo9Counter == 0xFFFF) return true;
675 if (not m_fillPatternOffset.isValid()) return true;
676 if (not m_fillPatternOffset->isCalibrated()) return true;
677
678 // fill pattern offset; it is always zero on MC, because we are not simulating it
679
680 int offset = m_isMC ? 0 : m_fillPatternOffset->get();
681
682 // corresponding bucket number and fill status
683
684 int RFBuckets = m_bunchStructure->getRFBucketsPerRevolution();
685 int bucket = TOPRecBunch::getBucketNumber(bunchNo, m_revo9Counter, offset, RFBuckets);
686 bool isFilled = m_bunchStructure->getBucket(bucket);
687
688 // store them in TOPRecBunch
689
690 m_recBunch->setBucketNumber(bucket);
691 m_recBunch->setBucketFillStatus(isFilled);
692
693 return isFilled;
694 }
695
696
698} // end Belle2 namespace
Container for likelihoods obtained by the CDC dE/dx PID (CDCDedxPIDModule).
Provides a type-safe way to pass members of the chargedStableSet set.
Definition Const.h:590
RestrictedDetectorSet< PIDDetectors > PIDDetectorSet
Typedef for set of PID detectors.
Definition Const.h:380
static const ParticleSet chargedStableSet
set of charged stable particles
Definition Const.h:619
static const ChargedStable pion
charged pion particle
Definition Const.h:662
static const ChargedStable proton
proton particle
Definition Const.h:664
static const ParticleType invalidParticle
Invalid particle, used internally.
Definition Const.h:682
static const ChargedStable kaon
charged kaon particle
Definition Const.h:663
int getPDG() const
Return PDG code of particle.
Definition MCParticle.h:101
void setDescription(const std::string &description)
Sets the description of the module.
Definition Module.cc:214
void setPropertyFlags(unsigned int propertyFlags)
Sets the flags for the module properties.
Definition Module.cc:208
Module()
Constructor.
Definition Module.cc:30
@ c_ParallelProcessingCertified
This module can be run in parallel processing mode safely (All I/O must be done through the data stor...
Definition Module.h:80
Class to collect log likelihoods from TOP, ARICH, dEdx, ECL and KLM aimed for output to mdst includes...
bool isRequired(const std::string &name="")
Ensure this array/object has been registered previously.
bool isOptional(const std::string &name="")
Tell the DataStore about an optional input.
Accessor to arrays stored in the data store.
Definition StoreArray.h:113
Type-safe access to single objects in the data store.
Definition StoreObjPtr.h:96
double m_maxD0
maximal absolute value of helix perigee distance
unsigned m_nTrackLimit
maximum number of tracks (inclusive) to use three particle hypotheses in fine search
StoreObjPtr< TOPRecBunch > m_recBunch
reconstructed bunch
bool m_correctDigits
subtract bunch time in TOPDigits
DBObjPtr< TOPFrontEndSetting > m_feSetting
front-end settings
StoreObjPtr< EventT0 > m_eventT0
event T0
double m_minDERatio
minimal ratio of detected over expected photons
double m_sigmaSmear
additional smearing of PDF in [ns]
DBObjPtr< TOPCalCommonT0 > m_commonT0
common T0 calibration constants
bool m_HLTmode
use running average to correct digits
unsigned short m_revo9Counter
number of system clocks since last revo9 marker
int m_nodEdxCount
counter of tracks with no dEdx, reset at each event
double m_runningError
error on running average
int m_bunchesPerSSTclk
number of bunches per SST clock
bool m_useTimeSeed
use CDC or SVD event T0 as seed
bool m_saveHistograms
flag to save histograms
double m_minSignal
minimal number of signal photons
double m_maxZ0
maximal absolute value of helix perigee z coordnate
bool m_useFillPattern
use know fill pattern to enhance efficiency
int m_numBins
number of bins to which the fine search region is divided
bool m_subtractRunningOffset
subtract running offset when running in HLT mode
bool m_autoRange
determine coarse range automatically
double m_runningOffset
running average of bunch offset
int m_minNHitsCDC
minimal number of hits in CDC
unsigned m_success
events with reconstructed bunch
OptionalDBObjPtr< TOPCalFillPatternOffset > m_fillPatternOffset
fill pattern offset
double m_timeRangeFine
time range in which to do fine search [ns]
StoreArray< Track > m_tracks
collection of tracks
DBObjPtr< BunchStructure > m_bunchStructure
fill pattern
bool m_useMCTruth
use MC truth for mass instead of dEdx most probable
double m_minPt
minimal p_T of track
double m_tau
first order filter time constant [events]
OptionalDBObjPtr< TOPCalEventT0Offset > m_eventT0Offset
detector components offsets w.r.t TOP
double m_maxDERatio
maximal ratio of detected over expected photons
bool m_usePIDLikelihoods
if true, use PIDLikelihoods (only on cdst files)
double m_maxPt
maximal p_T of track
StoreArray< TOPRawDigit > m_topRawDigits
collection of TOP raw digits
unsigned m_processed
processed events
StoreArray< TOPTimeZero > m_timeZeros
collection of T0 of individual tracks
double m_bunchTimeSep
time between two bunches
double m_timeRangeCoarse
time range in which to do coarse search if autoRange turned off [ns]
std::map< int, double > m_priors
map of PDG codes to prior probabilities
StoreArray< TOPDigit > m_topDigits
collection of TOP digits
StoreObjPtr< MCInitialParticles > m_initialParticles
simulated beam particles
double m_minSBRatio
minimal signal-to-background ratio
const TOPNominalTDC & getNominalTDC() const
Returns nominal time-to-digit conversion parameters.
@ c_syncWindows
number of windows corresponding to syncTimeBase
int getBucketNumber() const
Returns reconstructed bucket number stored in private member.
Minimum finder using tabulated chi^2 values in one dimension.
Binned one dimensional PDF (a projection of PDF to time axis)
Definition PDF1Dim.h:25
double getExpectedSignal() const
Returns expected number of signal photons.
Definition PDF1Dim.h:73
double getExpectedDeltaPhotons() const
Returns expected number of delta-ray photons.
Definition PDF1Dim.h:79
double getExpectedBG() const
Returns expected number of background photons.
Definition PDF1Dim.h:85
int getNumOfPhotons() const
Returns number of photons.
Definition PDF1Dim.h:67
PDF construction and log likelihood determination for a given track and particle hypothesis.
LogL getBackgroundLogL() const
Returns extended log likelihood for background hypothesis using default time window.
void switchOffDeltaRayPDF() const
Exclude delta-ray PDF in log likelihood calculation.
LogL getLogL() const
Returns extended log likelihood (using the default time window)
bool isValid() const
Checks the object status.
double getExpectedSignalPhotons() const
Returns the expected number of signal photons within the default time window.
@ c_Rough
no dependence on y
const TOPGeometry * getGeometry() const
Returns pointer to geometry object using basf2 units.
static TOPGeometryPar * Instance()
Static method to obtain the pointer to its instance.
static void setDefaultTimeWindow()
Sets default time window (functions getMinTime(), getMaxTime() will then return default values from D...
static double getMaxTime()
Returns time window upper edge.
static double getMinTime()
Returns time window lower edge.
Reconstructed track at TOP.
Definition TOPTrack.h:41
const MCParticle * getMCParticle() const
Returns MC particle assigned to this track (if any)
Definition TOPTrack.h:230
bool isValid() const
Checks if track is successfully constructed.
Definition TOPTrack.h:145
double getMomentumMag() const
Returns momentum magnitude (extrapolated to TOP)
Definition TOPTrack.h:157
const TOPBarHit * getBarHit() const
Returns bar hit of MC particle assigned to this track (if any)
Definition TOPTrack.h:246
Class that bundles various TrackFitResults.
Definition Track.h:25
Container for likelihoods obtained by the VXD dE/dx PID (VXDDedxPIDModule).
void addParam(const std::string &name, T &paramVariable, const std::string &description, const T &defaultValue)
Adds a new parameter to the module.
Definition Module.h:560
#define REG_MODULE(moduleName)
Register the given module (without 'Module' suffix) with the framework.
Definition Module.h:650
double sqrt(double a)
sqrt for double
Definition beamHelpers.h:28
virtual void initialize() override
Initialize the Module.
virtual void event() override
Event processor.
Const::ChargedStable getMostProbable(const Track &track)
Returns most probable charged stable particle according to dEdx and predefined prior probabilities.
virtual void terminate() override
Termination action.
bool isBucketFilled(int bunchNo)
Does reconstructed bunch number correspond to filled bucket.
virtual void beginRun() override
Called when entering a new run.
int setFinder(TOP::Chi2MinimumFinder1D &finder, const TOP::PDFConstructor &reco, double timeMin, double timeMax)
Sets finder object with chi2 values.
TimeSeed getTimeSeed()
Returns a time seed.
Abstract base class for different kinds of events.
STL namespace.
Structure for storing the extracted event t0s together with its detector and its uncertainty.
Definition EventT0.h:33
Structure to hold the time seed from a chosen detector component.
Const::EDetector detector
detector component
double logL
extended log likelihood