Belle II Software development
MillepedeCollectorModule.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 <alignment/modules/MillepedeCollector/MillepedeCollectorModule.h>
10
11#include <alignment/dataobjects/MilleData.h>
12#include <alignment/GblMultipleScatteringController.h>
13#include <alignment/GlobalDerivatives.h>
14#include <alignment/GlobalLabel.h>
15#include <alignment/GlobalParam.h>
16#include <alignment/GlobalTimeLine.h>
17#include <alignment/Manager.h>
18#include <alignment/reconstruction/AlignableCDCRecoHit.h>
19#include <alignment/reconstruction/AlignablePXDRecoHit.h>
20#include <alignment/reconstruction/AlignableSVDRecoHit.h>
21#include <alignment/reconstruction/AlignableSVDRecoHit2D.h>
22#include <alignment/reconstruction/AlignableBKLMRecoHit.h>
23#include <alignment/reconstruction/AlignableEKLMRecoHit.h>
24#include <analysis/dataobjects/ParticleList.h>
25#include <analysis/utility/ReferenceFrame.h>
26#include <framework/core/FileCatalog.h>
27#include <framework/database/DBObjPtr.h>
28#include <framework/dataobjects/FileMetaData.h>
29#include <framework/datastore/StoreArray.h>
30#include <framework/dbobjects/BeamParameters.h>
31#include <framework/particledb/EvtGenDatabasePDG.h>
32#include <framework/pcore/ProcHandler.h>
33#include <mdst/dbobjects/BeamSpot.h>
34#include <mdst/dataobjects/Track.h>
35#include <tracking/trackFitting/fitter/base/TrackFitter.h>
36#include <tracking/trackFitting/measurementCreator/adder/MeasurementAdder.h>
37
38#include <genfit/FullMeasurement.h>
39#include <genfit/GblFitter.h>
40#include <genfit/KalmanFitterInfo.h>
41#include <genfit/PlanarMeasurement.h>
42#include <genfit/Track.h>
43
44#include <TMath.h>
45#include <TH1F.h>
46#include <TTree.h>
47#include <TDecompSVD.h>
48
49using namespace std;
50using namespace Belle2;
51using namespace alignment;
52
53//-----------------------------------------------------------------
54// Register the Module
55//-----------------------------------------------------------------
56REG_MODULE(MillepedeCollector);
57
58//-----------------------------------------------------------------
59// Implementation
60//-----------------------------------------------------------------
61
63{
65 setDescription("Calibration data collector for Millepede Algorithm");
66
67 // Configure input sample types
68 addParam("tracks", m_tracks, "Names of collections of RecoTracks (already fitted with DAF) for calibration", vector<string>({""}));
69 addParam("particles", m_particles, "Names of particle list of single particles", vector<string>());
70 addParam("vertices", m_vertices,
71 "Name of particle list of (mother) particles with daughters for calibration using vertex constraint", vector<string>());
72 addParam("primaryVertices", m_primaryVertices,
73 "Name of particle list of (mother) particles with daughters for calibration using vertex + IP profile constraint",
74 vector<string>());
75 addParam("twoBodyDecays", m_twoBodyDecays,
76 "Name of particle list of (mother) particles with daughters for calibration using vertex + mass constraint",
77 vector<string>());
78 addParam("primaryTwoBodyDecays", m_primaryTwoBodyDecays,
79 "Name of particle list of (mother) particles with daughters for calibration using vertex + IP profile + kinematics constraint",
80 vector<string>());
81 addParam("primaryMassTwoBodyDecays", m_primaryMassTwoBodyDecays,
82 "Name of particle list of (mother) particles with daughters for calibration using vertex + mass constraint",
83 vector<string>());
84 addParam("primaryMassVertexTwoBodyDecays", m_primaryMassVertexTwoBodyDecays,
85 "Name of particle list of (mother) particles with daughters for calibration using vertex + IP profile + mass constraint",
86 vector<string>());
87
88 addParam("stableParticleWidth", m_stableParticleWidth,
89 "Width (in GeV/c/c) to use for invariant mass constraint for 'stable' particles (like K short). Temporary until proper solution is found.",
90 double(0.002));
91 // Configure output
92 addParam("doublePrecision", m_doublePrecision, "Use double (=true) or single/float (=false) precision for writing binary files",
93 bool(false));
94 addParam("useGblTree", m_useGblTree, "Store GBL trajectories in a tree instead of output to binary files",
95 bool(true));
96 addParam("absFilePaths", m_absFilePaths, "Use absolute paths to remember binary files. Only applies if useGblTree=False",
97 bool(false));
98
99 // Configure global parameters
100 addParam("components", m_components,
101 "Specify which DB objects are calibrated, like ['BeamSpot', 'CDCTimeWalks'] or leave empty to use all components available.",
103 addParam("calibrateVertex", m_calibrateVertex,
104 "For primary vertices / two body decays, beam spot vertex calibration derivatives are added",
105 bool(true));
106 addParam("calibrateKinematics", m_calibrateKinematics,
107 "For primary two body decays, beam spot kinematics calibration derivatives are added",
108 bool(true));
109
110 //Configure GBL fit of individual tracks
111 addParam("externalIterations", m_externalIterations, "Number of external iterations of GBL fitter",
112 int(0));
113 addParam("internalIterations", m_internalIterations, "String defining internal GBL iterations for outlier down-weighting",
114 string(""));
115 addParam("recalcJacobians", m_recalcJacobians, "Up to which external iteration propagation Jacobians should be re-calculated",
116 int(0));
117
118 addParam("minPValue", m_minPValue, "Minimum p-value to write out a (combined) trajectory. Set <0 to write out all.",
119 double(-1.));
120
121 // Configure CDC specific options
122 addParam("fitTrackT0", m_fitTrackT0, "Add local parameter for track T0 fit in GBL",
123 bool(true));
124 addParam("updateCDCWeights", m_updateCDCWeights, "Update L/R weights from previous DAF fit result",
125 bool(true));
126 addParam("minCDCHitWeight", m_minCDCHitWeight, "Minimum (DAF) CDC hit weight for usage by GBL",
127 double(1.0E-6));
128 addParam("minUsedCDCHitFraction", m_minUsedCDCHitFraction, "Minimum used CDC hit fraction to write out a trajectory",
129 double(0.85));
130
131 addParam("hierarchyType", m_hierarchyType, "Type of (VXD only now) hierarchy: 0 = None, 1 = Flat, 2 = Half-Shells, 3 = Full",
132 int(3));
133 addParam("enablePXDHierarchy", m_enablePXDHierarchy, "Enable PXD in hierarchy (flat or full)",
134 bool(true));
135 addParam("enableSVDHierarchy", m_enableSVDHierarchy, "Enable SVD in hierarchy (flat or full)",
136 bool(true));
137
138 addParam("enableWireByWireAlignment", m_enableWireByWireAlignment, "Enable global derivatives for wire-by-wire alignment",
139 bool(false));
140 addParam("enableWireSagging", m_enableWireSagging, "Enable global derivatives for wire sagging",
141 bool(false));
142
143 // Time dependence
144 addParam("events", m_eventNumbers,
145 "List of (event, run, exp) with event numbers at which payloads can change for timedep calibration.",
147 // Time dependence config
148 addParam("timedepConfig", m_timedepConfig,
149 "list{ {list{param1, param2, ...}, list{(ev1, run1, exp1), ...}}, ... }.",
151
152 // Custom mass+width config
153 addParam("customMassConfig", m_customMassConfig,
154 "dict{ list_name: (mass, width), ... } with custom mass and width to use as external measurement.",
156}
157
159{
160 m_eventT0.isOptional();
161
162 if (m_tracks.empty() &&
163 m_particles.empty() &&
164 m_vertices.empty() &&
165 m_primaryVertices.empty() &&
166 m_twoBodyDecays.empty() &&
167 m_primaryTwoBodyDecays.empty() &&
170 B2ERROR("You have to specify either arrays of single tracks or particle lists of single single particles or mothers with vertex constrained daughters.");
171
172 if (!m_tracks.empty()) {
173 for (auto arrayName : m_tracks)
174 continue;
175 // StoreArray<RecoTrack>::required(arrayName);
176 }
177
178 if (!m_particles.empty() || !m_vertices.empty() || !m_primaryVertices.empty()) {
179 // StoreArray<RecoTrack> recoTracks;
180 // StoreArray<Track> tracks;
181 // StoreArray<TrackFitResult> trackFitResults;
182
183 //recoTracks.isRequired();
184 //tracks.isRequired();
185 //trackFitResults.isRequired();
186 }
187
188 for (auto listName : m_particles) {
189 StoreObjPtr<ParticleList> list(listName);
190 //list.isRequired();
191 }
192
193 for (auto listName : m_vertices) {
194 StoreObjPtr<ParticleList> list(listName);
195 //list.isRequired();
196 }
197
198 for (auto listName : m_primaryVertices) {
199 StoreObjPtr<ParticleList> list(listName);
200 //list.isRequired();
201 }
202
203 // Register Mille output
205
206 auto gblDataTree = new TTree("GblDataTree", "GblDataTree");
207 gblDataTree->Branch<std::vector<gbl::GblData>>("GblData", &m_currentGblData, 32000, 99);
208 registerObject<TTree>("GblDataTree", gblDataTree);
209
210 registerObject<TH1I>("ndf", new TH1I("ndf", "ndf", 200, 0, 200));
211 registerObject<TH1F>("chi2_per_ndf", new TH1F("chi2_per_ndf", "chi2 divided by ndf", 200, 0., 50.));
212 registerObject<TH1F>("pval", new TH1F("pval", "pval", 100, 0., 1.));
213
214 registerObject<TH1F>("cdc_hit_fraction", new TH1F("cdc_hit_fraction", "cdc_hit_fraction", 100, 0., 1.));
215 registerObject<TH1F>("evt0", new TH1F("evt0", "evt0", 400, -100., 100.));
216
217 // Configure the (VXD) hierarchy before being built
218 if (m_hierarchyType == 0)
219 Belle2::alignment::VXDGlobalParamInterface::s_hierarchyType = VXDGlobalParamInterface::c_None;
220 else if (m_hierarchyType == 1)
221 Belle2::alignment::VXDGlobalParamInterface::s_hierarchyType = VXDGlobalParamInterface::c_Flat;
222 else if (m_hierarchyType == 2)
223 Belle2::alignment::VXDGlobalParamInterface::s_hierarchyType = VXDGlobalParamInterface::c_HalfShells;
224 else if (m_hierarchyType == 3)
225 Belle2::alignment::VXDGlobalParamInterface::s_hierarchyType = VXDGlobalParamInterface::c_Full;
226
229
230 std::vector<EventMetaData> events;
231 for (auto& ev_run_exp : m_eventNumbers) {
232 events.push_back(EventMetaData(std::get<0>(ev_run_exp), std::get<1>(ev_run_exp), std::get<2>(ev_run_exp)));
233 }
234
235 // This will also build the hierarchy for the first time:
236 if (!m_timedepConfig.empty() && m_eventNumbers.empty()) {
237 auto autoEvents = Belle2::alignment::timeline::setupTimedepGlobalLabels(m_timedepConfig);
239 } else if (m_timedepConfig.empty() && !m_eventNumbers.empty()) {
241 } else if (m_timedepConfig.empty() && m_eventNumbers.empty()) {
243 } else {
244 B2ERROR("Cannot set both, event list and timedep config.");
245 }
246
247// Belle2::alignment::GlobalCalibrationManager::getInstance().writeConstraints("constraints.txt");
248
252}
253
255{
257
258 if (!m_useGblTree) {
259 // Open new file on request (at start or after being closed)
260 auto mille = getObjectPtr<MilleData>("mille");
261 if (!mille->isOpen())
262 mille->open(getUniqueMilleName());
263 }
264
265 std::shared_ptr<genfit::GblFitter> gbl(new genfit::GblFitter());
266 double chi2 = -1.;
267 double lostWeight = -1.;
268 int ndf = -1;
269 float evt0 = -9999.;
270
271 for (auto arrayName : m_tracks) {
272 StoreArray<RecoTrack> recoTracks(arrayName);
273 if (!recoTracks.isValid())
274 continue;
275
276 for (auto& recoTrack : recoTracks) {
277
278 if (!fitRecoTrack(recoTrack))
279 continue;
280
281 auto& track = RecoTrackGenfitAccess::getGenfitTrack(recoTrack);
282 if (!track.hasFitStatus())
283 continue;
284 genfit::GblFitStatus* fs = dynamic_cast<genfit::GblFitStatus*>(track.getFitStatus());
285 if (!fs)
286 continue;
287
288 if (!fs->isFittedWithReferenceTrack())
289 continue;
290
291 using namespace gbl;
292 GblTrajectory trajectory(gbl->collectGblPoints(&track, track.getCardinalRep()), fs->hasCurvature());
293
294 trajectory.fit(chi2, ndf, lostWeight);
295 getObjectPtr<TH1I>("ndf")->Fill(ndf);
296 getObjectPtr<TH1F>("chi2_per_ndf")->Fill(chi2 / double(ndf));
297 getObjectPtr<TH1F>("pval")->Fill(TMath::Prob(chi2, ndf));
298 if (m_eventT0.isValid() && m_eventT0->hasEventT0()) {
299 evt0 = m_eventT0->getEventT0();
300 getObjectPtr<TH1F>("evt0")->Fill(evt0);
301 }
302
303 if (TMath::Prob(chi2, ndf) > m_minPValue) storeTrajectory(trajectory);
304
305 }
306
307 }
308
309 for (auto listName : m_particles) {
310 StoreObjPtr<ParticleList> list(listName);
311 if (!list.isValid())
312 continue;
313
314 for (unsigned int iParticle = 0; iParticle < list->getListSize(); ++iParticle) {
315 for (auto& track : getParticlesTracks({list->getParticle(iParticle)}, false)) {
316 auto gblfs = dynamic_cast<genfit::GblFitStatus*>(track->getFitStatus());
317
318 gbl::GblTrajectory trajectory(gbl->collectGblPoints(track, track->getCardinalRep()), gblfs->hasCurvature());
319
320 trajectory.fit(chi2, ndf, lostWeight);
321 getObjectPtr<TH1I>("ndf")->Fill(ndf);
322 getObjectPtr<TH1F>("chi2_per_ndf")->Fill(chi2 / double(ndf));
323 getObjectPtr<TH1F>("pval")->Fill(TMath::Prob(chi2, ndf));
324 if (m_eventT0.isValid() && m_eventT0->hasEventT0()) {
325 evt0 = m_eventT0->getEventT0();
326 getObjectPtr<TH1F>("evt0")->Fill(evt0);
327 }
328
329 if (TMath::Prob(chi2, ndf) > m_minPValue) storeTrajectory(trajectory);
330
331 }
332 }
333 }
334
335 for (auto listName : m_vertices) {
336 StoreObjPtr<ParticleList> list(listName);
337 if (!list.isValid())
338 continue;
339
340 for (unsigned int iParticle = 0; iParticle < list->getListSize(); ++iParticle) {
341 auto mother = list->getParticle(iParticle);
342 std::vector<std::pair<std::vector<gbl::GblPoint>, TMatrixD> > daughters;
343
344 for (auto& track : getParticlesTracks(mother->getDaughters()))
345 daughters.push_back({
346 gbl->collectGblPoints(track, track->getCardinalRep()),
347 getGlobalToLocalTransform(track->getFittedState()).GetSub(0, 4, 0, 2)
348 });
349
350 if (daughters.size() > 1) {
351 gbl::GblTrajectory combined(daughters);
352
353 combined.fit(chi2, ndf, lostWeight);
354 getObjectPtr<TH1I>("ndf")->Fill(ndf);
355 getObjectPtr<TH1F>("chi2_per_ndf")->Fill(chi2 / double(ndf));
356 getObjectPtr<TH1F>("pval")->Fill(TMath::Prob(chi2, ndf));
357 if (m_eventT0.isValid() && m_eventT0->hasEventT0()) {
358 evt0 = m_eventT0->getEventT0();
359 getObjectPtr<TH1F>("evt0")->Fill(evt0);
360 }
361
362
363 if (TMath::Prob(chi2, ndf) > m_minPValue) storeTrajectory(combined);
364
365 B2RESULT("Vertex-constrained fit NDF = " << ndf << " Chi2/NDF = " << chi2 / double(ndf));
366
367 }
368 }
369 }
370
371 for (auto listName : m_primaryVertices) {
372 StoreObjPtr<ParticleList> list(listName);
373 if (!list.isValid())
374 continue;
375
376 for (unsigned int iParticle = 0; iParticle < list->getListSize(); ++iParticle) {
377 auto mother = list->getParticle(iParticle);
378 std::vector<std::pair<std::vector<gbl::GblPoint>, TMatrixD> > daughters;
379
380 TMatrixD extProjection(5, 3);
381 TMatrixD locProjection(3, 5);
382
383 // geometric constaint: 3 common (position) parameters + 3 external (curv., directions) per daughter
384 //TODO: revert due to alignment issues in rel9 (!5184)
385 //TMatrixD innerTrafo(5, 3 + 3 * mother->getDaughters().size());
386 //unsigned int iCol(3);
387
388 bool first(true);
389 for (auto& track : getParticlesTracks(mother->getDaughters())) {
390 if (first) {
391 // For first trajectory only
392 extProjection = getGlobalToLocalTransform(track->getFittedState()).GetSub(0, 4, 0, 2);
393 locProjection = getLocalToGlobalTransform(track->getFittedState()).GetSub(0, 2, 0, 4);
394 first = false;
395 }
396
397 //TODO: revert due to alignment issues in rel9 (!5184)
398 //innerTrafo.Zero();
399 //innerTrafo.SetSub(3, 0, getGlobalToLocalTransform(track->getFittedState()).GetSub(3, 4, 0, 2));
400 //innerTrafo[0][iCol++] = 1.;
401 //innerTrafo[1][iCol++] = 1.;
402 //innerTrafo[2][iCol++] = 1.;
403
404
405 daughters.push_back({
406 gbl->collectGblPoints(track, track->getCardinalRep()),
407 //TODO: revert due to alignment issues in rel9 (!5184)
408 //innerTrafo
409 getGlobalToLocalTransform(track->getFittedState()).GetSub(0, 4, 0, 2)
410 });
411 }
412
413 if (daughters.size() > 1) {
414 auto beam = getPrimaryVertexAndCov();
415
416 TMatrixDSym vertexCov(get<TMatrixDSym>(beam));
417 TMatrixDSym vertexPrec(get<TMatrixDSym>(beam).Invert());
418 B2Vector3D vertexResidual = - (B2Vector3D(mother->getVertex()) - get<B2Vector3D>(beam));
419
420 TVectorD extMeasurements(3);
421 extMeasurements[0] = vertexResidual[0];
422 extMeasurements[1] = vertexResidual[1];
423 extMeasurements[2] = vertexResidual[2];
424
425 //TODO: revert due to alignment issues in rel9 (!5184)
426 //TMatrixD extDeriv(3, 9);
427 TMatrixD extDeriv(3, 3);
428 extDeriv.Zero();
429 // beam vertex constraint
430 extDeriv(0, 0) = 1.;
431 extDeriv(1, 1) = 1.;
432 extDeriv(2, 2) = 1.;
433
434 if (m_calibrateVertex) {
435 TMatrixD derivatives(3, 3);
436 derivatives.Zero();
437 derivatives(0, 0) = 1.;
438 derivatives(1, 1) = 1.;
439 derivatives(2, 2) = 1.;
440
441 std::vector<int> labels;
443 labels.push_back(label.setParameterId(1));
444 labels.push_back(label.setParameterId(2));
445 labels.push_back(label.setParameterId(3));
446
447 // Allow to disable BeamSpot externally
448 alignment::GlobalDerivatives globals(labels, derivatives);
449 // Add derivatives for vertex calibration to first point of first trajectory
450 // NOTE: use GlobalDerivatives operators vector<int> and TMatrixD which filter
451 // the derivatives to not pass those with zero labels (useful to get rid of some params)
452 std::vector<int> lab(globals); TMatrixD der(globals);
453
454 // Transformation from local system at (vertex) point to global (vx,vy,vz)
455 // of the (decay) vertex
456 //
457 // d(q/p,u',v',u,v)/d(vy,vy,vz) = dLocal_dExt
458 //
459 //
460 // Note its transpose is its "inverse" in the sense that
461 //
462 // dloc/dext * (dloc/dext)^T = diag(0, 0, 0, 0, 1, 1)
463 //
464 //
465 // N.B. typical dLocal_dExt matrix (5x3):
466 //
467 // | 0 | 1 | 2 |
468 // --------------------------------------------
469 // 0 | 0 0 0
470 // 1 | 0 0 0
471 // 2 | 0 0 0
472 // 3 | -0.02614 -0.9997 0
473 // 4 | 0 0 1
474 //
475 // Therefore one can simplify things by only taking the last two rows/columns in vectors/matrices
476 // and vertex measurement can be expressed as standard 2D measurement in GBL.
477 //
478 TMatrixD dLocal_dExt = extProjection;
479 TMatrixD dExt_dLocal = locProjection;
480
481 TVectorD locRes = dLocal_dExt * extMeasurements;
482 // Do not use inverted covariance - seems to have issues with numeric precision
483 TMatrixD locCov = dLocal_dExt * vertexCov * dExt_dLocal;
484 // Invert here only the 2D sub-matrix (rest is zero due to the foŕm of dLocal_dExt)
485 TMatrixD locPrec = locCov.GetSub(3, 4, 3, 4).Invert();
486 TMatrixDSym locPrec2D(2); locPrec2D.Zero();
487 for (int i = 0; i < 2; ++i)
488 for (int j = 0; j < 2; ++j)
489 locPrec2D(i, j) = locPrec(i, j);
490
491 // Take the 2 last components also for residuals and global derivatives
492 // (in local system of vertex point - defined during fitRecoTrack(..., particle) and using
493 // the (hopefully) updated momentum and position seed after vertex fit by modularAnalysis
494 TVectorD locRes2D = locRes.GetSub(3, 4);
495 TMatrixD locDerivs2D = (extProjection * der).GetSub(3, 4, 0, 2);
496
497 // Attach the primary beamspot vertex position as a measurement at 1st point
498 // of first trajectory (and optionally also the global derivatives for beamspot alignment
499 daughters[0].first[0].addMeasurement(locRes2D, locPrec2D);
500 if (!lab.empty()) {
501 daughters[0].first[0].addGlobals(lab, locDerivs2D);
502 }
503
504 gbl::GblTrajectory combined(daughters);
505 //combined.printTrajectory(100);
506 //combined.printPoints(100);
507
508 combined.fit(chi2, ndf, lostWeight);
509 getObjectPtr<TH1I>("ndf")->Fill(ndf);
510 getObjectPtr<TH1F>("chi2_per_ndf")->Fill(chi2 / double(ndf));
511 getObjectPtr<TH1F>("pval")->Fill(TMath::Prob(chi2, ndf));
512 if (m_eventT0.isValid() && m_eventT0->hasEventT0()) {
513 evt0 = m_eventT0->getEventT0();
514 getObjectPtr<TH1F>("evt0")->Fill(evt0);
515 }
516
517 if (TMath::Prob(chi2, ndf) > m_minPValue) storeTrajectory(combined);
518 B2RESULT("Beam vertex constrained fit results NDF = " << ndf << " Chi2/NDF = " << chi2 / double(ndf));
519
520 } else {
521
522 gbl::GblTrajectory combined(daughters, extDeriv, extMeasurements, vertexPrec);
523
524 combined.fit(chi2, ndf, lostWeight);
525 getObjectPtr<TH1I>("ndf")->Fill(ndf);
526 getObjectPtr<TH1F>("chi2_per_ndf")->Fill(chi2 / double(ndf));
527 getObjectPtr<TH1F>("pval")->Fill(TMath::Prob(chi2, ndf));
528 if (m_eventT0.isValid() && m_eventT0->hasEventT0()) {
529 evt0 = m_eventT0->getEventT0();
530 getObjectPtr<TH1F>("evt0")->Fill(evt0);
531 }
532
533 if (TMath::Prob(chi2, ndf) > m_minPValue) storeTrajectory(combined);
534
535 B2RESULT("Beam vertex constrained fit results NDF = " << ndf << " Chi2/NDF = " << chi2 / double(ndf));
536
537 }
538 }
539 }
540 }
541
542 for (auto listName : m_twoBodyDecays) {
543 StoreObjPtr<ParticleList> list(listName);
544 if (!list.isValid())
545 continue;
546
547 for (unsigned int iParticle = 0; iParticle < list->getListSize(); ++iParticle) {
548
549 auto mother = list->getParticle(iParticle);
550 auto track12 = getParticlesTracks(mother->getDaughters());
551 if (track12.size() != 2) {
552 B2ERROR("Did not get 2 fitted tracks. Skipping this mother.");
553 continue;
554 }
555
556 auto pdgdb = EvtGenDatabasePDG::Instance();
557 double motherMass = mother->getPDGMass();
558 double motherWidth = pdgdb->GetParticle(mother->getPDGCode())->Width();
559
560 updateMassWidthIfSet(listName, motherMass, motherWidth);
561
562 //TODO: what to take as width for "real" particles? -> make a param for default detector mass resolution??
563 if (motherWidth == 0.) {
564 motherWidth = m_stableParticleWidth * Unit::GeV;
565 B2WARNING("Using artificial width for " << pdgdb->GetParticle(mother->getPDGCode())->GetName() << " : " << motherWidth << " GeV");
566 }
567
568 auto dfdextPlusMinus = getTwoBodyToLocalTransform(*mother, motherMass);
569 std::vector<std::pair<std::vector<gbl::GblPoint>, TMatrixD> > daughters;
570
571 daughters.push_back({gbl->collectGblPoints(track12[0], track12[0]->getCardinalRep()), dfdextPlusMinus.first});
572 daughters.push_back({gbl->collectGblPoints(track12[1], track12[1]->getCardinalRep()), dfdextPlusMinus.second});
573
574 TMatrixDSym massPrec(1); massPrec(0, 0) = 1. / motherWidth / motherWidth;
575 TVectorD massResidual(1); massResidual = - (mother->getMass() - motherMass);
576
577 TVectorD extMeasurements(1);
578 extMeasurements[0] = massResidual[0];
579
580 TMatrixD extDeriv(1, 9);
581 extDeriv.Zero();
582 extDeriv(0, 8) = 1.;
583
584 gbl::GblTrajectory combined(daughters, extDeriv, extMeasurements, massPrec);
585
586 combined.fit(chi2, ndf, lostWeight);
587 //combined.printTrajectory(1000);
588 //combined.printPoints(1000);
589 getObjectPtr<TH1I>("ndf")->Fill(ndf);
590 getObjectPtr<TH1F>("chi2_per_ndf")->Fill(chi2 / double(ndf));
591 getObjectPtr<TH1F>("pval")->Fill(TMath::Prob(chi2, ndf));
592 if (m_eventT0.isValid() && m_eventT0->hasEventT0()) {
593 evt0 = m_eventT0->getEventT0();
594 getObjectPtr<TH1F>("evt0")->Fill(evt0);
595 }
596
597
598 B2RESULT("Mass(PDG) + vertex constrained fit results NDF = " << ndf << " Chi2/NDF = " << chi2 / double(ndf));
599
600 if (TMath::Prob(chi2, ndf) > m_minPValue) storeTrajectory(combined);
601
602 }
603 }
604
605 for (auto listName : m_primaryMassTwoBodyDecays) {
606 StoreObjPtr<ParticleList> list(listName);
607 if (!list.isValid())
608 continue;
609
611
612 double motherMass = beam->getMass();
613 double motherWidth = sqrt((beam->getCovHER() + beam->getCovLER())(0, 0));
614
615 updateMassWidthIfSet(listName, motherMass, motherWidth);
616
617 for (unsigned int iParticle = 0; iParticle < list->getListSize(); ++iParticle) {
618
619 auto mother = list->getParticle(iParticle);
620 auto track12 = getParticlesTracks(mother->getDaughters());
621 if (track12.size() != 2) {
622 B2ERROR("Did not get 2 fitted tracks. Skipping this mother.");
623 continue;
624 }
625
626 auto dfdextPlusMinus = getTwoBodyToLocalTransform(*mother, motherMass);
627 std::vector<std::pair<std::vector<gbl::GblPoint>, TMatrixD> > daughters;
628
629 daughters.push_back({gbl->collectGblPoints(track12[0], track12[0]->getCardinalRep()), dfdextPlusMinus.first});
630 daughters.push_back({gbl->collectGblPoints(track12[1], track12[1]->getCardinalRep()), dfdextPlusMinus.second});
631
632 TMatrixDSym massPrec(1); massPrec(0, 0) = 1. / motherWidth / motherWidth;
633 TVectorD massResidual(1); massResidual = - (mother->getMass() - motherMass);
634
635 TVectorD extMeasurements(1);
636 extMeasurements[0] = massResidual[0];
637
638 TMatrixD extDeriv(1, 9);
639 extDeriv.Zero();
640 extDeriv(0, 8) = 1.;
641
642 gbl::GblTrajectory combined(daughters, extDeriv, extMeasurements, massPrec);
643
644 combined.fit(chi2, ndf, lostWeight);
645 getObjectPtr<TH1I>("ndf")->Fill(ndf);
646 getObjectPtr<TH1F>("chi2_per_ndf")->Fill(chi2 / double(ndf));
647 getObjectPtr<TH1F>("pval")->Fill(TMath::Prob(chi2, ndf));
648 if (m_eventT0.isValid() && m_eventT0->hasEventT0()) {
649 evt0 = m_eventT0->getEventT0();
650 getObjectPtr<TH1F>("evt0")->Fill(evt0);
651 }
652
653
654 B2RESULT("Mass constrained fit results NDF = " << ndf << " Chi2/NDF = " << chi2 / double(ndf));
655
656 if (TMath::Prob(chi2, ndf) > m_minPValue) storeTrajectory(combined);
657
658 }
659 }
660
661 for (auto listName : m_primaryMassVertexTwoBodyDecays) {
662 StoreObjPtr<ParticleList> list(listName);
663 if (!list.isValid())
664 continue;
665
667
668 double motherMass = beam->getMass();
669 double motherWidth = sqrt((beam->getCovHER() + beam->getCovLER())(0, 0));
670
671 updateMassWidthIfSet(listName, motherMass, motherWidth);
672
673 for (unsigned int iParticle = 0; iParticle < list->getListSize(); ++iParticle) {
674
675 auto mother = list->getParticle(iParticle);
676 auto track12 = getParticlesTracks(mother->getDaughters());
677 if (track12.size() != 2) {
678 B2ERROR("Did not get 2 fitted tracks. Skipping this mother.");
679 continue;
680 }
681
682 auto dfdextPlusMinus = getTwoBodyToLocalTransform(*mother, motherMass);
683 std::vector<std::pair<std::vector<gbl::GblPoint>, TMatrixD> > daughters;
684
685 daughters.push_back({gbl->collectGblPoints(track12[0], track12[0]->getCardinalRep()), dfdextPlusMinus.first});
686 daughters.push_back({gbl->collectGblPoints(track12[1], track12[1]->getCardinalRep()), dfdextPlusMinus.second});
687
688 TMatrixDSym vertexPrec(get<TMatrixDSym>(getPrimaryVertexAndCov()).Invert());
689 B2Vector3D vertexResidual = - (B2Vector3D(mother->getVertex()) - get<B2Vector3D>(getPrimaryVertexAndCov()));
690
691 TMatrixDSym massPrec(1); massPrec(0, 0) = 1. / motherWidth / motherWidth;
692 TVectorD massResidual(1); massResidual = - (mother->getMass() - motherMass);
693
694 TMatrixDSym extPrec(4); extPrec.Zero();
695 extPrec.SetSub(0, 0, vertexPrec);
696 extPrec(3, 3) = massPrec(0, 0);
697
698 TVectorD extMeasurements(4);
699 extMeasurements[0] = vertexResidual[0];
700 extMeasurements[1] = vertexResidual[1];
701 extMeasurements[2] = vertexResidual[2];
702 extMeasurements[3] = massResidual[0];
703
704 TMatrixD extDeriv(4, 9);
705 extDeriv.Zero();
706 extDeriv(0, 0) = 1.;
707 extDeriv(1, 1) = 1.;
708 extDeriv(2, 2) = 1.;
709 extDeriv(3, 8) = 1.;
710
711 gbl::GblTrajectory combined(daughters, extDeriv, extMeasurements, extPrec);
712
713 combined.fit(chi2, ndf, lostWeight);
714 getObjectPtr<TH1I>("ndf")->Fill(ndf);
715 getObjectPtr<TH1F>("chi2_per_ndf")->Fill(chi2 / double(ndf));
716 getObjectPtr<TH1F>("pval")->Fill(TMath::Prob(chi2, ndf));
717 if (m_eventT0.isValid() && m_eventT0->hasEventT0()) {
718 evt0 = m_eventT0->getEventT0();
719 getObjectPtr<TH1F>("evt0")->Fill(evt0);
720 }
721
722
723 if (TMath::Prob(chi2, ndf) > m_minPValue) storeTrajectory(combined);
724
725 B2RESULT("Mass + vertex constrained fit results NDF = " << ndf << " Chi2/NDF = " << chi2 / double(ndf));
726
727 }
728 }
729
730 for (auto listName : m_primaryTwoBodyDecays) {
731 B2WARNING("This should NOT be used for production of calibration constants for the real detector (yet)!");
732
733 StoreObjPtr<ParticleList> list(listName);
734 if (!list.isValid())
735 continue;
736
738
739 // For the error of invariant mass M = 2 * sqrt(E_HER * E_LER) (for m_e ~ 0)
740 double M = beam->getMass();
741 double E_HER = beam->getHER().E();
742 double E_LER = beam->getLER().E();
743
744 double pz = beam->getHER().Pz() + beam->getLER().Pz();
745 double E = (beam->getHER() + beam->getLER()).E();
746
747 double motherMass = beam->getMass();
748 double motherWidth = sqrt((E_HER / M) * (E_HER / M) * beam->getCovLER()(0, 0) + (E_LER / M) * (E_LER / M) * beam->getCovHER()(0,
749 0));
750
751 updateMassWidthIfSet(listName, motherMass, motherWidth);
752
753 for (unsigned int iParticle = 0; iParticle < list->getListSize(); ++iParticle) {
754
755 B2WARNING("Two body decays with full kinematic constraint not yet correct - need to resolve strange covariance provided by BeamParameters!");
756
757 auto mother = list->getParticle(iParticle);
758
759 auto track12 = getParticlesTracks(mother->getDaughters());
760 if (track12.size() != 2) {
761 B2ERROR("Did not get exactly 2 fitted tracks. Skipping this mother in list " << listName);
762 continue;
763 }
764
765 auto dfdextPlusMinus = getTwoBodyToLocalTransform(*mother, motherMass);
766 std::vector<std::pair<std::vector<gbl::GblPoint>, TMatrixD> > daughters;
767
768 daughters.push_back({gbl->collectGblPoints(track12[0], track12[0]->getCardinalRep()), dfdextPlusMinus.first});
769 daughters.push_back({gbl->collectGblPoints(track12[1], track12[1]->getCardinalRep()), dfdextPlusMinus.second});
770
771 TMatrixDSym extCov(7); extCov.Zero();
772
773 // 3x3 IP vertex covariance
774 extCov.SetSub(0, 0, get<TMatrixDSym>(getPrimaryVertexAndCov()));
775
776 // 3x3 boost vector covariance
777 //NOTE: BeamSpot return covarince in variables (E, theta_x, theta_y)
778 // We need to transform it to our variables (px, py, pz)
779
780 TMatrixD dBoost_dVect(3, 3);
781 dBoost_dVect(0, 0) = 0.; dBoost_dVect(0, 1) = 1. / pz; dBoost_dVect(0, 2) = 0.;
782 dBoost_dVect(1, 0) = 0.; dBoost_dVect(1, 1) = 0.; dBoost_dVect(1, 2) = 1. / pz;
783 dBoost_dVect(2, 0) = pz / E; dBoost_dVect(2, 1) = 0.; dBoost_dVect(2, 2) = 0.;
784
785 TMatrixD dVect_dBoost(3, 3);
786 dVect_dBoost(0, 0) = 0.; dVect_dBoost(0, 1) = 0.; dVect_dBoost(0, 2) = E / pz;
787 dVect_dBoost(1, 0) = pz; dVect_dBoost(1, 1) = 0.; dVect_dBoost(1, 2) = 0.;
788 dVect_dBoost(2, 0) = 0.; dVect_dBoost(2, 1) = pz; dVect_dBoost(2, 2) = 0.;
789
790 TMatrixD covBoost(3, 3);
791 for (int i = 0; i < 3; ++i) {
792 for (int j = i; j < 3; ++j) {
793 covBoost(j, i) = covBoost(i, j) = (beam->getCovHER() + beam->getCovLER())(i, j);
794 }
795 }
796 //TODO: Temporary fix: if theta_x, theta_y covariance is zero, use arbitrary 10mrad^2
797// if (covBoost(1, 1) == 0.) covBoost(1, 1) = 1.;
798// if (covBoost(2, 2) == 0.) covBoost(2, 2) = 1.;
799 if (covBoost(1, 1) == 0.) covBoost(1, 1) = 1.e-4;
800 if (covBoost(2, 2) == 0.) covBoost(2, 2) = 1.e-4;
801
802 TMatrixD covVect = dBoost_dVect * covBoost * dVect_dBoost;
803
804 extCov.SetSub(3, 3, covVect);
805
806 extCov(6, 6) = motherWidth * motherWidth;
807 auto extPrec = extCov; extPrec.Invert();
808
809 TVectorD extMeasurements(7);
810 extMeasurements[0] = - (B2Vector3D(mother->getVertex()) - get<B2Vector3D>(getPrimaryVertexAndCov()))[0];
811 extMeasurements[1] = - (B2Vector3D(mother->getVertex()) - get<B2Vector3D>(getPrimaryVertexAndCov()))[1];
812 extMeasurements[2] = - (B2Vector3D(mother->getVertex()) - get<B2Vector3D>(getPrimaryVertexAndCov()))[2];
813 extMeasurements[3] = - (B2Vector3D(mother->getMomentum()) - (beam->getHER().Vect() + beam->getLER().Vect()))[0];
814 extMeasurements[4] = - (B2Vector3D(mother->getMomentum()) - (beam->getHER().Vect() + beam->getLER().Vect()))[1];
815 extMeasurements[5] = - (B2Vector3D(mother->getMomentum()) - (beam->getHER().Vect() + beam->getLER().Vect()))[2];
816 extMeasurements[6] = - (mother->getMass() - motherMass);
817
818 B2INFO("mother mass = " << mother->getMass() << " and beam mass = " << beam->getMass());
819
820 TMatrixD extDeriv(7, 9);
821 extDeriv.Zero();
822 // beam vertex constraint
823 extDeriv(0, 0) = 1.;
824 extDeriv(1, 1) = 1.;
825 extDeriv(2, 2) = 1.;
826 // beam kinematics constraint
827 extDeriv(3, 3) = 1.;
828 extDeriv(4, 4) = 1.;
829 extDeriv(5, 5) = 1.;
830 // beam inv. mass constraint
831 extDeriv(6, 8) = 1;
832
834 B2WARNING("Primary vertex+kinematics calibration not (yet?) fully implemented!");
835 B2WARNING("This code is highly experimental and has (un)known issues!");
836
837 // up to d(x,y,z,px,py,pz,theta,phi,M)/d(vx,vy,vz,theta_x,theta_y,E)
838 TMatrixD derivatives(9, 6);
839 std::vector<int> labels;
840 derivatives.Zero();
841
842 if (m_calibrateVertex) {
843 derivatives(0, 0) = 1.;
844 derivatives(1, 1) = 1.;
845 derivatives(2, 2) = 1.;
847 labels.push_back(label.setParameterId(1));
848 labels.push_back(label.setParameterId(2));
849 labels.push_back(label.setParameterId(3));
850 } else {
851 labels.push_back(0);
852 labels.push_back(0);
853 labels.push_back(0);
854 }
855
857 derivatives(3, 3) = mother->getMomentumMagnitude();
858 derivatives(4, 4) = mother->getMomentumMagnitude();
859 derivatives(8, 5) = (beam->getLER().E() + beam->getHER().E()) / beam->getMass();
860
862 labels.push_back(label.setParameterId(4)); //theta_x
863 labels.push_back(label.setParameterId(5)); //theta_y
864 labels.push_back(label.setParameterId(6)); //E
865
866 } else {
867 labels.push_back(0);
868 labels.push_back(0);
869 labels.push_back(0);
870 }
871
872 // Allow to disable BeamSpot externally
873 alignment::GlobalDerivatives globals(labels, derivatives);
874
875 // Add derivatives for vertex calibration to first point of first trajectory
876 // NOTE: use GlobalDerivatives operators vector<int> and TMatrixD which filter
877 // the derivatives to not pass those with zero labels (useful to get rid of some params)
878 std::vector<int> lab(globals); TMatrixD der(globals);
879
880 // I want: dlocal/dext = dlocal/dtwobody * dtwobody/dext = dfdextPlusMinus * dtwobody/dext
881 TMatrixD dTwoBody_dExt(9, 7);
882 dTwoBody_dExt.Zero();
883 // beam vertex constraint
884 dTwoBody_dExt(0, 0) = 1.;
885 dTwoBody_dExt(1, 1) = 1.;
886 dTwoBody_dExt(2, 2) = 1.;
887 // beam kinematics constraint
888 dTwoBody_dExt(3, 3) = 1.;
889 dTwoBody_dExt(4, 4) = 1.;
890 dTwoBody_dExt(5, 5) = 1.;
891 // beam inv. mass constraint
892 dTwoBody_dExt(8, 6) = 1.;
893
894 const TMatrixD dLocal_dExt = dfdextPlusMinus.first * dTwoBody_dExt;
895 TMatrixD dLocal_dExt_T = dLocal_dExt; dLocal_dExt_T.T();
896
897 // The 5x7 transformation matrix d(q/p,u',v',u,v)/d(vx,vy,vz,px,py,pz,M) needs to be "inverted"
898 // to transform the covariance of the beamspot and boost vector of SuperKEKB into the local system
899 // of one GBL point - such that Millepede can align the beamspot (or even beam kinematics) if requested.
900 //
901 // I tested also other methods, but only the Singular Value Decomposition gives nice-enough results,
902 // with almost no code:
903 //
904 TDecompSVD svd(dLocal_dExt_T);
905 TMatrixD dExt_dLocal = svd.Invert().T();
906 //
907 // (dLocal_dExt * dExt_dLocal).Print(); // Check how close we are to unit matrix
908 //
909 // 5x5 matrix is as follows
910 //
911 // | 0 | 1 | 2 | 3 | 4 |
912 // ----------------------------------------------------------------------
913 // 0 | 1 -2.58e-17 6.939e-18 1.571e-17 -1.649e-19
914 // 1 | 1.787e-14 1 5.135e-16 -3.689e-16 -2.316e-18
915 // 2 | -1.776e-15 -7.806e-17 1 5.636e-17 6.193e-18
916 // 3 | -2.453e-15 7.26e-18 2.009e-16 1 -1.14e-16
917 // 4 | -1.689e-14 -9.593e-17 -2.317e-15 -3.396e-17 1
918 //
919 // It took me half a day to find out how to do this with 2 lines of code (3 with the include).
920 // Source: ROOT macro example - actually found at:
921 // <https://root.cern.ch/root/html/tutorials/matrix/solveLinear.C.html>
922 for (int i = 0; i < 7; ++i) {
923 for (int j = 0; j < 5; ++j) {
924 if (fabs(dExt_dLocal(i, j)) < 1.e-6)
925 dExt_dLocal(i, j) = 0.;
926 }
927 }
928 const TVectorD locRes = dLocal_dExt * extMeasurements;
929 const TMatrixD locPrec = dLocal_dExt * extPrec * dExt_dLocal;
930
931 TMatrixDSym locPrecSym(5); locPrecSym.Zero();
932 for (int i = 0; i < 5; ++i) {
933 for (int j = i; j < 5; ++j) {
934 //locPrecSym(j, i) = locPrecSym(i, j) = locPrec(i, j);
935 locPrecSym(j, i) = locPrecSym(i, j) = (fabs(locPrec(i, j)) > 1.e-6) ? locPrec(i, j) : 0.;
936 }
937 }
938
939 daughters[0].first[0].addMeasurement(locRes, locPrecSym);
940 if (!lab.empty())
941 daughters[0].first[0].addGlobals(lab, dfdextPlusMinus.first * der);
942
943 //TODO: Understand this: either find a bug somewhere or improve the parametrization or .... ?
944 // This should be enough, but the parametrization seems to fail for nearly horizontal pairs...
945 //gbl::GblTrajectory combined(daughters);
946 // This should not be needed, it actually seems to make worse Chi2/NDF, but GBL does not fail.
947 // The measurement added just to be able to add the global derivatives (done just above) is redundant
948 // to the external measurement added here:
949 gbl::GblTrajectory combined(daughters, extDeriv, extMeasurements, extPrec);
950 //combined.printTrajectory(1000);
951 //combined.printPoints(1000);
952
953 combined.fit(chi2, ndf, lostWeight);
954 getObjectPtr<TH1I>("ndf")->Fill(ndf);
955 getObjectPtr<TH1F>("chi2_per_ndf")->Fill(chi2 / double(ndf));
956 getObjectPtr<TH1F>("pval")->Fill(TMath::Prob(chi2, ndf));
957 if (m_eventT0.isValid() && m_eventT0->hasEventT0()) {
958 evt0 = m_eventT0->getEventT0();
959 getObjectPtr<TH1F>("evt0")->Fill(evt0);
960 }
961
962
963 B2RESULT("Full kinematic-constrained fit (calibration version) results NDF = " << ndf << " Chi2/NDF = " << chi2 / double(ndf));
964
965 if (TMath::Prob(chi2, ndf) > m_minPValue) storeTrajectory(combined);
966
967 } else {
968
969 gbl::GblTrajectory combined(daughters, extDeriv, extMeasurements, extPrec);
970 //combined.printTrajectory(1000);
971 //combined.printPoints(1000);
972
973 combined.fit(chi2, ndf, lostWeight);
974 getObjectPtr<TH1I>("ndf")->Fill(ndf);
975 getObjectPtr<TH1F>("chi2_per_ndf")->Fill(chi2 / double(ndf));
976 getObjectPtr<TH1F>("pval")->Fill(TMath::Prob(chi2, ndf));
977 if (m_eventT0.isValid() && m_eventT0->hasEventT0()) {
978 evt0 = m_eventT0->getEventT0();
979 getObjectPtr<TH1F>("evt0")->Fill(evt0);
980 }
981
982
983 B2RESULT("Full kinematic-constrained fit results NDF = " << ndf << " Chi2/NDF = " << chi2 / double(ndf));
984
985 if (TMath::Prob(chi2, ndf) > m_minPValue) storeTrajectory(combined);
986 }
987 }
988 }
989}
990
992{
993 // We close the file at end of run, producing
994 // one file per run (and process id) which is more
995 // convenient than one large binary block.
996 auto mille = getObjectPtr<MilleData>("mille");
997 if (mille->isOpen())
998 mille->close();
999}
1000
1002{
1004
1006 if (!fileMetaData.isValid()) {
1007 B2ERROR("Cannot register binaries in FileCatalog.");
1008 return;
1009 }
1010
1011
1012 const std::vector<string> parents = {fileMetaData->getLfn()};
1013 for (auto binary : getObjectPtr<MilleData>("mille")->getFiles()) {
1014 FileMetaData milleMetaData(*fileMetaData);
1015 // We reset filename to be set directly by the registerFile procedure
1016 milleMetaData.setLfn("");
1017 milleMetaData.setParents(parents);
1018 FileCatalog::Instance().registerFile(binary, milleMetaData);
1019 }
1020
1021}
1022
1023void MillepedeCollectorModule::storeTrajectory(gbl::GblTrajectory& trajectory)
1024{
1025 if (m_useGblTree) {
1026 if (trajectory.isValid())
1027 m_currentGblData = trajectory.getData();
1028 else
1029 m_currentGblData.clear();
1030
1031 if (!m_currentGblData.empty())
1032 getObjectPtr<TTree>("GblDataTree")->Fill();
1033 } else {
1034 getObjectPtr<MilleData>("mille")->fill(trajectory);
1035 }
1036}
1037
1039{
1040 string name = getName();
1041
1042 name += "-e" + to_string(m_evtMetaData->getExperiment());
1043 name += "-r" + to_string(m_evtMetaData->getRun());
1044 name += "-ev" + to_string(m_evtMetaData->getEvent());
1045
1047 name += "-pid" + to_string(ProcHandler::EvtProcID());
1048
1049 name += ".mille";
1050
1051 return name;
1052}
1053
1055{
1056 try {
1057 // For already fitted tracks, try to get fitted (DAF) weights for CDC
1058 if (m_updateCDCWeights && recoTrack.getNumberOfCDCHits() && recoTrack.getTrackFitStatus()
1059 && recoTrack.getTrackFitStatus()->isFitted()) {
1060 double sumCDCWeights = recoTrack.getNumberOfCDCHits(); // start with full weights
1061 // Do the hits synchronisation
1062 auto relatedRecoHitInformation =
1064
1065 for (RecoHitInformation& recoHitInformation : relatedRecoHitInformation) {
1066
1067 if (recoHitInformation.getFlag() == RecoHitInformation::c_pruned) {
1068 B2FATAL("Found pruned point in RecoTrack. Pruned tracks cannot be used in MillepedeCollector.");
1069 }
1070
1071 if (recoHitInformation.getTrackingDetector() != RecoHitInformation::c_CDC) continue;
1072
1073 const genfit::TrackPoint* trackPoint = recoTrack.getCreatedTrackPoint(&recoHitInformation);
1074 if (trackPoint) {
1075 if (not trackPoint->hasFitterInfo(recoTrack.getCardinalRepresentation()))
1076 continue;
1077 auto kalmanFitterInfo = dynamic_cast<genfit::KalmanFitterInfo*>(trackPoint->getFitterInfo());
1078 if (not kalmanFitterInfo) {
1079 continue;
1080 } else {
1081 std::vector<double> weights = kalmanFitterInfo->getWeights();
1082 if (weights.size() == 2) {
1083 if (weights.at(0) > weights.at(1))
1084 recoHitInformation.setRightLeftInformation(RecoHitInformation::c_left);
1085 else if (weights.at(0) < weights.at(1))
1086 recoHitInformation.setRightLeftInformation(RecoHitInformation::c_right);
1087
1088 double weightLR = weights.at(0) + weights.at(1);
1089 if (weightLR < m_minCDCHitWeight) recoHitInformation.setUseInFit(false);
1090 sumCDCWeights += weightLR - 1.; // reduce weight sum if weightLR<1
1091 }
1092 }
1093 }
1094 }
1095
1096 double usedCDCHitFraction = sumCDCWeights / double(recoTrack.getNumberOfCDCHits());
1097 getObjectPtr<TH1F>("cdc_hit_fraction")->Fill(usedCDCHitFraction);
1098 if (usedCDCHitFraction < m_minUsedCDCHitFraction)
1099 return false;
1100 }
1101 } catch (...) {
1102 B2ERROR("Error in checking DAF weights from previous fit to resolve hit ambiguity. Why? Failed fit points in DAF? Skip track to be sure.");
1103 return false;
1104 }
1105
1106 std::shared_ptr<genfit::GblFitter> gbl(new genfit::GblFitter());
1107 gbl->setOptions(m_internalIterations, true, true, m_externalIterations, m_recalcJacobians);
1108 gbl->setTrackSegmentController(new GblMultipleScatteringController);
1109
1110 MeasurementAdder factory("", "", "", "", "");
1111
1112 // We need the store arrays
1118
1119 // Create the genfit::MeasurementFactory
1120 genfit::MeasurementFactory<genfit::AbsMeasurement> genfitMeasurementFactory;
1121
1122 // Add producer for alignable RecoHits to factory
1123 if (pxdHits.isOptional()) {
1124 genfit::MeasurementProducer <RecoHitInformation::UsedPXDHit, AlignablePXDRecoHit>* PXDProducer = new genfit::MeasurementProducer
1126 genfitMeasurementFactory.addProducer(Const::PXD, PXDProducer);
1127 }
1128
1129 if (svdHits.isOptional()) {
1130 genfit::MeasurementProducer <RecoHitInformation::UsedSVDHit, AlignableSVDRecoHit>* SVDProducer = new genfit::MeasurementProducer
1132 genfitMeasurementFactory.addProducer(Const::SVD, SVDProducer);
1133 }
1134
1135 if (cdcHits.isOptional()) {
1136 genfit::MeasurementProducer <RecoHitInformation::UsedCDCHit, AlignableCDCRecoHit>* CDCProducer = new genfit::MeasurementProducer
1138 genfitMeasurementFactory.addProducer(Const::CDC, CDCProducer);
1139 }
1140
1141 if (bklmHits.isOptional()) {
1142 genfit::MeasurementProducer <RecoHitInformation::UsedBKLMHit, AlignableBKLMRecoHit>* BKLMProducer = new genfit::MeasurementProducer
1144 genfitMeasurementFactory.addProducer(Const::BKLM, BKLMProducer);
1145 }
1146
1147 if (eklmHits.isOptional()) {
1148 genfit::MeasurementProducer <RecoHitInformation::UsedEKLMHit, AlignableEKLMRecoHit>* EKLMProducer = new genfit::MeasurementProducer
1150 genfitMeasurementFactory.addProducer(Const::EKLM, EKLMProducer);
1151 }
1152
1153
1154 // Create the measurement creators
1155 std::vector<std::shared_ptr<PXDBaseMeasurementCreator>> pxdMeasurementCreators = { std::shared_ptr<PXDBaseMeasurementCreator>(new PXDCoordinateMeasurementCreator(genfitMeasurementFactory)) };
1156 std::vector<std::shared_ptr<SVDBaseMeasurementCreator>> svdMeasurementCreators = { std::shared_ptr<SVDBaseMeasurementCreator>(new SVDCoordinateMeasurementCreator(genfitMeasurementFactory)) };
1157 // TODO: Create a new MeasurementCreator based on SVDBaseMeasurementCreator (or on SVDCoordinateMeasurementCreator), which does the combination on the fly.
1158
1159 std::vector<std::shared_ptr<CDCBaseMeasurementCreator>> cdcMeasurementCreators = { std::shared_ptr<CDCBaseMeasurementCreator>(new CDCCoordinateMeasurementCreator(genfitMeasurementFactory)) };
1160 std::vector<std::shared_ptr<BKLMBaseMeasurementCreator>> bklmMeasurementCreators = { std::shared_ptr<BKLMBaseMeasurementCreator>(new BKLMCoordinateMeasurementCreator(genfitMeasurementFactory)) };
1161 std::vector<std::shared_ptr<EKLMBaseMeasurementCreator>> eklmMeasurementCreators = { std::shared_ptr<EKLMBaseMeasurementCreator>(new EKLMCoordinateMeasurementCreator(genfitMeasurementFactory)) };
1162
1163 // TODO: Or put it in here and leave the svdMeasurementCreators empty.
1164 std::vector<std::shared_ptr<BaseMeasurementCreator>> additionalMeasurementCreators = {};
1165 factory.resetMeasurementCreators(pxdMeasurementCreators, svdMeasurementCreators, cdcMeasurementCreators, bklmMeasurementCreators,
1166 eklmMeasurementCreators, additionalMeasurementCreators);
1167 factory.addMeasurements(recoTrack);
1168
1169 auto& gfTrack = RecoTrackGenfitAccess::getGenfitTrack(recoTrack);
1170
1171 int currentPdgCode = TrackFitter::createCorrectPDGCodeForChargedStable(Const::muon, recoTrack);
1172 if (particle)
1173 currentPdgCode = particle->getPDGCode();
1174
1175 genfit::AbsTrackRep* trackRep = RecoTrackGenfitAccess::createOrReturnRKTrackRep(recoTrack, currentPdgCode);
1176 gfTrack.setCardinalRep(gfTrack.getIdForRep(trackRep));
1177
1178 if (particle) {
1179 B2Vector3D vertexPos = particle->getVertex();
1180 B2Vector3D vertexMom = particle->getMomentum();
1181 gfTrack.setStateSeed(vertexPos, vertexMom);
1182
1183 genfit::StateOnPlane vertexSOP(gfTrack.getCardinalRep());
1184 B2Vector3D vertexRPhiDir(vertexPos[0], vertexPos[1], 0);
1185 B2Vector3D vertexZDir(0, 0, vertexPos[2]);
1186 //FIXME: This causes problem to current GBL version in genfit -> needs update of GBL to re-enable
1187 // genfit::SharedPlanePtr vertexPlane(new genfit::DetPlane(vertexPos, vertexRPhiDir, vertexZDir));
1188 //This works instead fine:
1189 genfit::SharedPlanePtr vertexPlane(new genfit::DetPlane(vertexPos, vertexMom));
1190
1191 vertexSOP.setPlane(vertexPlane);
1192 vertexSOP.setPosMom(vertexPos, vertexMom);
1193 TMatrixDSym vertexCov(5);
1194 vertexCov.UnitMatrix();
1195 // By using negative covariance no measurement is added to GBL. But this first point
1196 // is then used as additional point in trajectory at the assumed point of its fitted vertex
1197 vertexCov *= -1.;
1198 genfit::MeasuredStateOnPlane mop(vertexSOP, vertexCov);
1199 genfit::FullMeasurement* vertex = new genfit::FullMeasurement(mop, Const::IR);
1200 gfTrack.insertMeasurement(vertex, 0);
1201 }
1202
1203 try {
1204 for (unsigned int i = 0; i < gfTrack.getNumPoints() - 1; ++i) {
1205 //if (gfTrack.getPointWithMeasurement(i)->getNumRawMeasurements() != 1)
1206 // continue;
1207 genfit::PlanarMeasurement* planarMeas1 = dynamic_cast<genfit::PlanarMeasurement*>(gfTrack.getPointWithMeasurement(
1208 i)->getRawMeasurement(0));
1209 genfit::PlanarMeasurement* planarMeas2 = dynamic_cast<genfit::PlanarMeasurement*>(gfTrack.getPointWithMeasurement(
1210 i + 1)->getRawMeasurement(0));
1211
1212 if (planarMeas1 != NULL && planarMeas2 != NULL &&
1213 planarMeas1->getDetId() == planarMeas2->getDetId() &&
1214 planarMeas1->getPlaneId() != -1 && // -1 is default plane id
1215 planarMeas1->getPlaneId() == planarMeas2->getPlaneId()) {
1216 Belle2::AlignableSVDRecoHit* hit1 = dynamic_cast<Belle2::AlignableSVDRecoHit*>(planarMeas1);
1217 Belle2::AlignableSVDRecoHit* hit2 = dynamic_cast<Belle2::AlignableSVDRecoHit*>(planarMeas2);
1218 if (hit1 && hit2) {
1219 Belle2::AlignableSVDRecoHit* hitU(NULL);
1220 Belle2::AlignableSVDRecoHit* hitV(NULL);
1221 // We have to decide U/V now (else AlignableSVDRecoHit2D could throw FATAL)
1222 if (hit1->isU() && !hit2->isU()) {
1223 hitU = hit1;
1224 hitV = hit2;
1225 } else if (!hit1->isU() && hit2->isU()) {
1226 hitU = hit2;
1227 hitV = hit1;
1228 } else {
1229 continue;
1230 }
1232 // insert measurement before point i (increases number of correct point to i+1)
1233 gfTrack.insertMeasurement(hit, i);
1234 // now delete current point (at its original place, we have the new 2D recohit)
1235 gfTrack.deletePoint(i + 1);
1236 gfTrack.deletePoint(i + 1);
1237 }
1238 }
1239 }
1240 } catch (std::exception& e) {
1241 B2ERROR(e.what());
1242 B2ERROR("SVD Cluster combination failed. This is symptomatic of pruned tracks. MillepedeCollector cannot process pruned tracks.");
1243 return false;
1244 }
1245
1246 try {
1247 gbl->processTrackWithRep(&gfTrack, gfTrack.getCardinalRep(), true);
1248 } catch (genfit::Exception& e) {
1249 B2ERROR(e.what());
1250 return false;
1251 } catch (...) {
1252 B2ERROR("GBL fit failed.");
1253 return false;
1254 }
1255
1256 return true;
1257}
1258
1259std::vector< genfit::Track* > MillepedeCollectorModule::getParticlesTracks(std::vector<Particle*> particles, bool addVertexPoint)
1260{
1261 std::vector< genfit::Track* > tracks;
1262 for (auto particle : particles) {
1263 auto belle2Track = particle->getTrack();
1264 if (!belle2Track) {
1265 B2WARNING("No Belle2::Track for particle (particle->X");
1266 continue;
1267 }
1268// auto trackFitResult = belle2Track->getTrackFitResult(Const::chargedStableSet.find(abs(particle->getPDGCode())));
1269// if (!trackFitResult) {
1270// B2INFO("No track fit result for track");
1271// continue;
1272// }
1273// auto recoTrack = trackFitResult->getRelatedFrom<RecoTrack>();
1274 auto recoTrack = belle2Track->getRelatedTo<RecoTrack>();
1275
1276 if (!recoTrack) {
1277 B2WARNING("No related RecoTrack for Belle2::Track (particle->Track->X)");
1278 continue;
1279 }
1280
1281 // If any track fails, fail completely
1282 if (!fitRecoTrack(*recoTrack, (addVertexPoint) ? particle : nullptr))
1283 return {};
1284
1285 auto& track = RecoTrackGenfitAccess::getGenfitTrack(*recoTrack);
1286
1287 if (!track.hasFitStatus()) {
1288 B2WARNING("Track has no fit status");
1289 continue;
1290 }
1291 genfit::GblFitStatus* fs = dynamic_cast<genfit::GblFitStatus*>(track.getFitStatus());
1292 if (!fs) {
1293 B2WARNING("Track FitStatus is not GblFitStatus.");
1294 continue;
1295 }
1296 if (!fs->isFittedWithReferenceTrack()) {
1297 B2WARNING("Track is not fitted with reference track.");
1298 continue;
1299 }
1300
1301 tracks.push_back(&track);
1302 }
1303
1304 return tracks;
1305}
1306
1308 double motherMass)
1309{
1310 std::vector<TMatrixD> result;
1311
1312 double px = mother.getPx();
1313 double py = mother.getPy();
1314 double pz = mother.getPz();
1315 double pt = sqrt(px * px + py * py);
1316 double p = mother.getMomentumMagnitude();
1317 double M = motherMass;
1318 double m = mother.getDaughter(0)->getPDGMass();
1319
1320 if (mother.getNDaughters() != 2
1321 || m != mother.getDaughter(1)->getPDGMass()) B2FATAL("Only two same-mass daughters (V0->f+f- decays) allowed.");
1322
1323 // Rotation matrix from mother reference system to lab system
1324 TMatrixD mother2lab(3, 3);
1325 mother2lab(0, 0) = px * pz / pt / p; mother2lab(0, 1) = - py / pt; mother2lab(0, 2) = px / p;
1326 mother2lab(1, 0) = py * pz / pt / p; mother2lab(1, 1) = px / pt; mother2lab(1, 2) = py / p;
1327 mother2lab(2, 0) = - pt / p; mother2lab(2, 1) = 0; mother2lab(2, 2) = pz / p;
1328 ROOT::Math::Rotation3D lab2mother;
1329 lab2mother.SetRotationMatrix(mother2lab); lab2mother.Invert();
1330
1331 // Need to rotate and boost daughters' momenta to know which goes forward (+sign in decay model)
1332 // and to get the angles theta, phi of the decaying daughter system in mothers' reference frame
1333 RestFrame boostedFrame(&mother);
1334 ROOT::Math::PxPyPzEVector fourVector1 = mother.getDaughter(0)->get4Vector();
1335 ROOT::Math::PxPyPzEVector fourVector2 = mother.getDaughter(1)->get4Vector();
1336
1337 auto mom1 = lab2mother * boostedFrame.getMomentum(fourVector1).Vect();
1338 auto mom2 = lab2mother * boostedFrame.getMomentum(fourVector2).Vect();
1339 // One momentum has opposite direction (otherwise should be same in CMS of mother), but which?
1340 double sign = 1.;
1341 auto avgMom = 0.5 * (mom1 - mom2);
1342 if (avgMom.Z() < 0.) {
1343 avgMom *= -1.;
1344 // switch meaning of plus/minus trajectories
1345 sign = -1.;
1346 }
1347
1348 double theta = atan2(avgMom.rho(), avgMom.Z());
1349 double phi = atan2(avgMom.Y(), avgMom.X());
1350 if (phi < 0.) phi += 2. * TMath::Pi();
1351
1352 double alpha = M / 2. / m;
1353 double c1 = m * sqrt(alpha * alpha - 1.);
1354 double c2 = 0.5 * sqrt((alpha * alpha - 1.) / alpha / alpha * (p * p + M * M));
1355
1356 double p3 = p * p * p;
1357 double pt3 = pt * pt * pt;
1358
1359
1360 for (auto& track : getParticlesTracks(mother.getDaughters())) {
1361
1362
1363 TMatrixD R = mother2lab;
1364 B2Vector3D P(sign * c1 * sin(theta) * cos(phi),
1365 sign * c1 * sin(theta) * sin(phi),
1366 p / 2. + sign * c2 * cos(theta));
1367
1368 TMatrixD dRdpx(3, 3);
1369 dRdpx(0, 0) = - pz * (pow(px, 4.) - pow(py, 4.) - py * py * pz * pz) / pt3 / p3;
1370 dRdpx(0, 1) = px * py / pt3;
1371 dRdpx(0, 2) = (py * py + pz * pz) / p3;
1372
1373 dRdpx(1, 0) = - px * py * pz * (2. * px * px + 2. * py * py + pz * pz) / pt3 / p3;
1374 dRdpx(1, 1) = - py * py / pt3;
1375 dRdpx(1, 2) = px * py / p3;
1376
1377 dRdpx(2, 0) = - px * pz * pz / pt / p3;
1378 dRdpx(2, 1) = 0.;
1379 dRdpx(2, 2) = - px * pz / p3;
1380
1381 TMatrixD dRdpy(3, 3);
1382 dRdpy(0, 0) = - px * py * pz * (2. * px * px + 2. * py * py + pz * pz) / pt3 / p3;
1383 dRdpy(0, 1) = - px * px / pt3;
1384 dRdpy(0, 2) = px * pz / p3;
1385
1386 dRdpy(1, 0) = - pz * (- pow(px, 4.) - px * px * pz * pz + pow(py, 4.)) / pt3 / p3;
1387 dRdpy(1, 1) = px * py / pt3;
1388 dRdpy(1, 2) = (px * px + pz * pz) / p3;
1389
1390 dRdpy(2, 0) = - py * pz * pz / pt / p3;
1391 dRdpy(2, 1) = 0.;
1392 dRdpy(2, 2) = - py * pz / p3;
1393
1394 TMatrixD dRdpz(3, 3);
1395 dRdpz(0, 0) = px * pt / p3;
1396 dRdpz(0, 1) = 0.;
1397 dRdpz(0, 2) = - px * pz / p3;
1398
1399 dRdpz(1, 0) = py * pt / p3;
1400 dRdpz(1, 1) = 0.;
1401 dRdpz(1, 2) = py * pz / p3;
1402
1403 dRdpz(2, 0) = pz * pt / p3;
1404 dRdpz(2, 1) = 0.;
1405 dRdpz(2, 2) = (px * px + py * py) / p3;
1406
1407 auto K = 1. / 2. / p + sign * cos(theta) * m * m * (M * M / 4. / m / m - 1.) / M / M / sqrt(m * m * (M * M / 4. / m / m - 1.) *
1408 (M * M + p * p) / M / M);
1409
1410 B2Vector3D dpdpx = dRdpx * P + R * K * px * B2Vector3D(0., 0., 1.);
1411 B2Vector3D dpdpy = dRdpy * P + R * K * py * B2Vector3D(0., 0., 1.);
1412 B2Vector3D dpdpz = dRdpz * P + R * K * pz * B2Vector3D(0., 0., 1.);
1413
1414 B2Vector3D dpdtheta = R * B2Vector3D(sign * c1 * cos(theta) * cos(phi),
1415 sign * c1 * cos(theta) * sin(phi),
1416 sign * c2 * (- sin(theta)));
1417
1418
1419 B2Vector3D dpdphi = R * B2Vector3D(sign * c1 * sin(theta) * (- sin(phi)),
1420 sign * c1 * sin(theta) * cos(phi),
1421 0.);
1422
1423 double dc1dM = m * M / (2. * sqrt(M * M - 4. * m * m));
1424 double dc2dM = M * (4. * m * m * p * p + pow(M, 4)) / (2 * M * M * M * sqrt((M * M - 4. * m * m) * (p * p + M * M)));
1425
1426 B2Vector3D dpdM = R * B2Vector3D(sign * sin(theta) * cos(phi) * dc1dM,
1427 sign * sin(theta) * sin(phi) * dc1dM,
1428 sign * cos(theta) * dc2dM);
1429
1430 TMatrixD dpdz(3, 6);
1431 dpdz(0, 0) = dpdpx(0); dpdz(0, 1) = dpdpy(0); dpdz(0, 2) = dpdpz(0); dpdz(0, 3) = dpdtheta(0); dpdz(0, 4) = dpdphi(0);
1432 dpdz(0, 5) = dpdM(0);
1433 dpdz(1, 0) = dpdpx(1); dpdz(1, 1) = dpdpy(1); dpdz(1, 2) = dpdpz(1); dpdz(1, 3) = dpdtheta(1); dpdz(1, 4) = dpdphi(1);
1434 dpdz(1, 5) = dpdM(1);
1435 dpdz(2, 0) = dpdpx(2); dpdz(2, 1) = dpdpy(2); dpdz(2, 2) = dpdpz(2); dpdz(2, 3) = dpdtheta(2); dpdz(2, 4) = dpdphi(2);
1436 dpdz(2, 5) = dpdM(2);
1437
1438 TMatrixD dqdv = getGlobalToLocalTransform(track->getFittedState()).GetSub(0, 4, 0, 2);
1439 TMatrixD dqdp = getGlobalToLocalTransform(track->getFittedState()).GetSub(0, 4, 3, 5);
1440 TMatrixD dfdvz(5, 9);
1441 dfdvz.SetSub(0, 0, dqdv);
1442 dfdvz.SetSub(0, 3, dqdp * dpdz);
1443
1444 result.push_back(dfdvz);
1445
1446 // switch sign for second trajectory
1447 sign *= -1.;
1448 }
1449
1450 return {result[0], result[1]};
1451}
1452
1453TMatrixD MillepedeCollectorModule::getGlobalToLocalTransform(const genfit::MeasuredStateOnPlane& msop)
1454{
1455 auto state = msop;
1456 const B2Vector3D& U(state.getPlane()->getU());
1457 const B2Vector3D& V(state.getPlane()->getV());
1458 const B2Vector3D& O(state.getPlane()->getO());
1459 const B2Vector3D& W(state.getPlane()->getNormal());
1460
1461 const double* state5 = state.getState().GetMatrixArray();
1462
1463 double spu = 1.;
1464
1465 const TVectorD& auxInfo = state.getAuxInfo();
1466 if (auxInfo.GetNrows() == 2
1467 || auxInfo.GetNrows() == 1) // backwards compatibility with old RKTrackRep
1468 spu = state.getAuxInfo()(0);
1469
1470 TVectorD state7(7);
1471
1472 state7[0] = O.X() + state5[3] * U.X() + state5[4] * V.X(); // x
1473 state7[1] = O.Y() + state5[3] * U.Y() + state5[4] * V.Y(); // y
1474 state7[2] = O.Z() + state5[3] * U.Z() + state5[4] * V.Z(); // z
1475
1476 state7[3] = spu * (W.X() + state5[1] * U.X() + state5[2] * V.X()); // a_x
1477 state7[4] = spu * (W.Y() + state5[1] * U.Y() + state5[2] * V.Y()); // a_y
1478 state7[5] = spu * (W.Z() + state5[1] * U.Z() + state5[2] * V.Z()); // a_z
1479
1480 // normalize dir
1481 double norm = 1. / sqrt(state7[3] * state7[3] + state7[4] * state7[4] + state7[5] * state7[5]);
1482 for (unsigned int i = 3; i < 6; ++i) state7[i] *= norm;
1483
1484 state7[6] = state5[0]; // q/p
1485
1486 const double AtU = state7[3] * U.X() + state7[4] * U.Y() + state7[5] * U.Z();
1487 const double AtV = state7[3] * V.X() + state7[4] * V.Y() + state7[5] * V.Z();
1488 const double AtW = state7[3] * W.X() + state7[4] * W.Y() + state7[5] * W.Z();
1489
1490 // J_Mp matrix is d(q/p,u',v',u,v) / d(x,y,z,px,py,pz) (in is 6x6)
1491
1492 const double qop = state7[6];
1493 const double p = state.getCharge() / qop; // momentum
1494
1495 TMatrixD J_Mp_6x5(6, 5);
1496 J_Mp_6x5.Zero();
1497
1498 //d(u)/d(x,y,z)
1499 J_Mp_6x5(0, 3) = U.X(); // [0][3]
1500 J_Mp_6x5(1, 3) = U.Y(); // [1][3]
1501 J_Mp_6x5(2, 3) = U.Z(); // [2][3]
1502 //d(v)/d(x,y,z)
1503 J_Mp_6x5(0, 4) = V.X(); // [0][4]
1504 J_Mp_6x5(1, 4) = V.Y(); // [1][4]
1505 J_Mp_6x5(2, 4) = V.Z(); // [2][4]
1506
1507 // d(q/p)/d(px,py,pz)
1508 double fact = (-1.) * qop / p;
1509 J_Mp_6x5(3, 0) = fact * state7[3]; // [3][0]
1510 J_Mp_6x5(4, 0) = fact * state7[4]; // [4][0]
1511 J_Mp_6x5(5, 0) = fact * state7[5]; // [5][0]
1512 // d(u')/d(px,py,pz)
1513 fact = 1. / (p * AtW * AtW);
1514 J_Mp_6x5(3, 1) = fact * (U.X() * AtW - W.X() * AtU); // [3][1]
1515 J_Mp_6x5(4, 1) = fact * (U.Y() * AtW - W.Y() * AtU); // [4][1]
1516 J_Mp_6x5(5, 1) = fact * (U.Z() * AtW - W.Z() * AtU); // [5][1]
1517 // d(v')/d(px,py,pz)
1518 J_Mp_6x5(3, 2) = fact * (V.X() * AtW - W.X() * AtV); // [3][2]
1519 J_Mp_6x5(4, 2) = fact * (V.Y() * AtW - W.Y() * AtV); // [4][2]
1520 J_Mp_6x5(5, 2) = fact * (V.Z() * AtW - W.Z() * AtV); // [5][2]
1521
1522 return J_Mp_6x5.T();
1523}
1524
1525TMatrixD MillepedeCollectorModule::getLocalToGlobalTransform(const genfit::MeasuredStateOnPlane& msop)
1526{
1527 auto state = msop;
1528 // get vectors and aux variables
1529 const B2Vector3D& U(state.getPlane()->getU());
1530 const B2Vector3D& V(state.getPlane()->getV());
1531 const B2Vector3D& W(state.getPlane()->getNormal());
1532
1533 const TVectorD& state5(state.getState());
1534 double spu = 1.;
1535
1536 const TVectorD& auxInfo = state.getAuxInfo();
1537 if (auxInfo.GetNrows() == 2
1538 || auxInfo.GetNrows() == 1) // backwards compatibility with old RKTrackRep
1539 spu = state.getAuxInfo()(0);
1540
1541 TVectorD pTilde(3);
1542 pTilde[0] = spu * (W.X() + state5(1) * U.X() + state5(2) * V.X()); // a_x
1543 pTilde[1] = spu * (W.Y() + state5(1) * U.Y() + state5(2) * V.Y()); // a_y
1544 pTilde[2] = spu * (W.Z() + state5(1) * U.Z() + state5(2) * V.Z()); // a_z
1545
1546 const double pTildeMag = sqrt(pTilde[0] * pTilde[0] + pTilde[1] * pTilde[1] + pTilde[2] * pTilde[2]);
1547 const double pTildeMag2 = pTildeMag * pTildeMag;
1548
1549 const double utpTildeOverpTildeMag2 = (U.X() * pTilde[0] + U.Y() * pTilde[1] + U.Z() * pTilde[2]) / pTildeMag2;
1550 const double vtpTildeOverpTildeMag2 = (V.X() * pTilde[0] + V.Y() * pTilde[1] + V.Z() * pTilde[2]) / pTildeMag2;
1551
1552 //J_pM matrix is d(x,y,z,px,py,pz) / d(q/p,u',v',u,v) (out is 6x6)
1553
1554 const double qop = state5(0);
1555 const double p = state.getCharge() / qop; // momentum
1556
1557 TMatrixD J_pM_5x6(5, 6);
1558 J_pM_5x6.Zero();
1559
1560 // d(px,py,pz)/d(q/p)
1561 double fact = -1. * p / (pTildeMag * qop);
1562 J_pM_5x6(0, 3) = fact * pTilde[0]; // [0][3]
1563 J_pM_5x6(0, 4) = fact * pTilde[1]; // [0][4]
1564 J_pM_5x6(0, 5) = fact * pTilde[2]; // [0][5]
1565 // d(px,py,pz)/d(u')
1566 fact = p * spu / pTildeMag;
1567 J_pM_5x6(1, 3) = fact * (U.X() - pTilde[0] * utpTildeOverpTildeMag2); // [1][3]
1568 J_pM_5x6(1, 4) = fact * (U.Y() - pTilde[1] * utpTildeOverpTildeMag2); // [1][4]
1569 J_pM_5x6(1, 5) = fact * (U.Z() - pTilde[2] * utpTildeOverpTildeMag2); // [1][5]
1570 // d(px,py,pz)/d(v')
1571 J_pM_5x6(2, 3) = fact * (V.X() - pTilde[0] * vtpTildeOverpTildeMag2); // [2][3]
1572 J_pM_5x6(2, 4) = fact * (V.Y() - pTilde[1] * vtpTildeOverpTildeMag2); // [2][4]
1573 J_pM_5x6(2, 5) = fact * (V.Z() - pTilde[2] * vtpTildeOverpTildeMag2); // [2][5]
1574 // d(x,y,z)/d(u)
1575 J_pM_5x6(3, 0) = U.X(); // [3][0]
1576 J_pM_5x6(3, 1) = U.Y(); // [3][1]
1577 J_pM_5x6(3, 2) = U.Z(); // [3][2]
1578 // d(x,y,z)/d(v)
1579 J_pM_5x6(4, 0) = V.X(); // [4][0]
1580 J_pM_5x6(4, 1) = V.Y(); // [4][1]
1581 J_pM_5x6(4, 2) = V.Z(); // [4][2]
1582
1583 return J_pM_5x6.T();
1584
1585}
1586
1587tuple<B2Vector3D, TMatrixDSym> MillepedeCollectorModule::getPrimaryVertexAndCov() const
1588{
1589 DBObjPtr<BeamSpot> beam;
1590 return {beam->getIPPosition(), beam->getSizeCovMatrix()};
1591}
1592
1593void MillepedeCollectorModule::updateMassWidthIfSet(string listName, double& mass, double& width)
1594{
1595 if (m_customMassConfig.find(listName) != m_customMassConfig.end()) {
1596 auto massWidth = m_customMassConfig.at(listName);
1597 mass = std::get<0>(massWidth);
1598 width = std::get<1>(massWidth);
1599 }
1600}
1601
R E
internal precision of FFTW codelets
double R
typedef autogenerated by FFTW
#define K(x)
macro autogenerated by FFTW
This class is used to transfer CDC information to the track fit and Millepede.
static bool s_enableWireSaggingGlobalDerivative
Static enabling(true) or disabling(false) addition of global derivative for wire sagging coefficient ...
static bool s_enableWireByWireAlignmentGlobalDerivatives
Static enabling(true) or disabling(false) addition of global derivatives for wire-by-wire alignment.
static bool s_enableTrackT0LocalDerivative
Static enabling(true) or disabling(false) addition of local derivative for track T0.
This class is used to transfer PXD information to the track fit.
This class is used to transfer SVD information to the track fit.
This class is used to transfer SVD information to the track fit.
DataType Z() const
access variable Z (= .at(2) without boundary check)
Definition B2Vector3.h:435
DataType X() const
access variable X (= .at(0) without boundary check)
Definition B2Vector3.h:431
DataType Y() const
access variable Y (= .at(1) without boundary check)
Definition B2Vector3.h:433
void registerObject(std::string name, T *obj)
Register object with a name, takes ownership, do not access the pointer beyond prepare()
CalibrationCollectorModule()
Constructor. Sets the default prefix for calibration dataobjects.
T * getObjectPtr(std::string name)
Calls the CalibObjManager to get the requested stored collector data.
static const ChargedStable muon
muon particle
Definition Const.h:660
Class for accessing objects in the database.
Definition DBObjPtr.h:21
@ c_Persistent
Object is available during entire execution time.
Definition DataStore.h:60
Store event, run, and experiment numbers.
static EvtGenDatabasePDG * Instance()
Instance method that loads the EvtGen table.
static FileCatalog & Instance()
Static method to get a reference to the FileCatalog instance.
virtual bool registerFile(const std::string &fileName, FileMetaData &metaData, const std::string &oldLFN="")
Register a file in the (local) file catalog.
Metadata information about a file.
void setLfn(const std::string &lfn)
Setter for LFN.
void setParents(const std::vector< std::string > &parents)
Parents setter.
TrackSegmentController for use with GblFitter in Belle2.
Class to convert to/from global labels for Millepede II to/from detector & parameter identificators.
Definition GlobalLabel.h:41
static GlobalLabel construct(gidTYPE element, gidTYPE param)
Construct label for given DB object (template argument) and its element and parameter.
Definition GlobalLabel.h:81
Algorithm class to translate the added detector hits (e.g.
void resetMeasurementCreators(const std::vector< std::shared_ptr< PXDBaseMeasurementCreator > > &pxdMeasurementCreators, const std::vector< std::shared_ptr< SVDBaseMeasurementCreator > > &svdMeasurementCreators, const std::vector< std::shared_ptr< CDCBaseMeasurementCreator > > &cdcMeasurementCreators, const std::vector< std::shared_ptr< BKLMBaseMeasurementCreator > > &bklmMeasurementCreators, const std::vector< std::shared_ptr< EKLMBaseMeasurementCreator > > &eklmMeasurementCreators, const std::vector< std::shared_ptr< BaseMeasurementCreator > > &additionalMeasurementCreators)
If you want to use non-default settings for the store arrays, you can create your own instances of th...
bool addMeasurements(RecoTrack &recoTrack) const
After you have filled the internal storage with measurement creators (either by providing your own or...
Mergeable class holding list of so far opened mille binaries and providing the binaries.
Definition MilleData.h:24
bool m_updateCDCWeights
Update L/R weights from previous DAF fit result?
std::vector< std::string > m_twoBodyDecays
Name of particle list with mothers of daughters to be used with vertex + mass constraint in calibrati...
TMatrixD getLocalToGlobalTransform(const genfit::MeasuredStateOnPlane &msop)
Compute the transformation matrix d(x,y,z,px,py,pz)/d(q/p,u',v',u,v) from state at first track point ...
std::vector< std::string > m_tracks
Names of arrays with single RecoTracks fitted by GBL.
MillepedeCollectorModule()
Constructor: Sets the description, the properties and the parameters of the module.
StoreObjPtr< EventT0 > m_eventT0
Optional input for EventT0.
std::vector< std::string > m_components
Whether to use VXD alignment hierarchy.
double m_minCDCHitWeight
Minimum CDC hit weight.
std::vector< std::string > m_primaryMassTwoBodyDecays
Name of particle list with mothers of daughters to be used with vertex + IP profile + mass constraint...
double m_minPValue
Minimum p.value for output.
std::string getUniqueMilleName()
Make a name for mille binary (encodes module name + starting exp, run and event + process id)
std::vector< std::tuple< int, int, int > > m_eventNumbers
List of event meta data entries at which payloads can change for timedep calibration.
bool m_absFilePaths
Use absolute path to locate binary files in MilleData.
std::vector< std::string > m_vertices
Name of particle list with mothers of daughters to be used with vertex constraint in calibration.
bool m_fitTrackT0
Add local parameter for track T0 fit in GBL (local derivative)
std::vector< genfit::Track * > getParticlesTracks(std::vector< Particle * > particles, bool addVertexPoint=true)
Get all usable tracks for particles.
std::vector< gbl::GblData > m_currentGblData
Current vector of GBL data from trajectory to be stored in a tree.
bool fitRecoTrack(RecoTrack &recoTrack, Particle *particle=nullptr)
Fit given RecoTrack with GBL.
bool m_enableWireSagging
Enable global derivatives for wire sagging.
TMatrixD getGlobalToLocalTransform(const genfit::MeasuredStateOnPlane &msop)
Compute the transformation matrix d(q/p,u',v',u,v)/d(x,y,z,px,py,pz) from state at first track point ...
std::tuple< B2Vector3D, TMatrixDSym > getPrimaryVertexAndCov() const
Get the primary vertex position estimation and its size from BeamSpot.
std::map< std::string, std::tuple< double, double > > m_customMassConfig
Map of list_name -> (mass, width) for custom mass and width setting.
int m_recalcJacobians
Up to which external iteration propagation Jacobians should be re-calculated.
bool m_useGblTree
Whether to use TTree to accumulate GBL data instead of binary files.
void storeTrajectory(gbl::GblTrajectory &trajectory)
Write down a GBL trajectory (to TTree or binary file)
bool m_doublePrecision
Use double (instead of single/float) precision for binary files.
virtual void collect() override
Data collection.
StoreObjPtr< EventMetaData > m_evtMetaData
Required object pointer to EventMetaData.
std::pair< TMatrixD, TMatrixD > getTwoBodyToLocalTransform(Particle &mother, double motherMass)
Compute the transformation matrices d(q/p,u'v',u,v)/d(vx,vy,vz,px,py,pz,theta,phi,...
bool m_enablePXDHierarchy
enable PXD hierarchy
virtual void closeRun() override
Only for closing mille binaries after each run.
bool m_calibrateKinematics
Add derivatives for beam spot kinematics calibration for primary vertices.
double m_minUsedCDCHitFraction
Minimum CDC used hit fraction.
void updateMassWidthIfSet(std::string listName, double &mass, double &width)
Update mass and width of the particle (mother in list) with user custom-defined values.
virtual void prepare() override
Prepration.
bool m_enableSVDHierarchy
enable SVD hierarchy
std::string m_internalIterations
String defining internal GBL iterations for outlier down-weighting.
std::vector< std::tuple< std::vector< int >, std::vector< std::tuple< int, int, int > > > > m_timedepConfig
Config for time dependence: list( tuple( list( param1, param2, ... ), list( (ev, run,...
std::vector< std::string > m_particles
Names of particle list with single particles.
virtual void finish() override
Register mille binaries in file catalog.
std::vector< std::string > m_primaryVertices
Name of particle list with mothers of daughters to be used with vertex + IP profile (+ optional calib...
int m_externalIterations
Number of external iterations of GBL fitter.
int m_hierarchyType
Type of alignment hierarchy (for VXD only for now): 0 = None, 1 = Flat (only constraints,...
bool m_enableWireByWireAlignment
Enable global derivatives for wire-by-wire alignment.
double m_stableParticleWidth
Width (in GeV/c/c) to use for invariant mass constraint for 'stable' particles (like K short).
std::vector< std::string > m_primaryTwoBodyDecays
Name of particle list with mothers of daughters to be used with vertex + IP profile (+ optional calib...
std::vector< std::string > m_primaryMassVertexTwoBodyDecays
Name of particle list with mothers of daughters to be used with vertex + IP profile + mass constraint...
bool m_calibrateVertex
Add derivatives for beam spot vertex calibration for primary vertices.
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
const std::string & getName() const
Returns the name of the module.
Definition Module.h:186
@ 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 store reconstructed particles.
Definition Particle.h:76
double getPx() const
Returns x component of momentum.
Definition Particle.h:607
double getPz() const
Returns z component of momentum.
Definition Particle.h:625
double getPy() const
Returns y component of momentum.
Definition Particle.h:616
unsigned getNDaughters(void) const
Returns number of daughter particles.
Definition Particle.h:747
double getPDGMass(void) const
Returns uncertainty on the invariant mass (requires valid momentum error matrix)
Definition Particle.cc:635
ROOT::Math::PxPyPzEVector get4Vector() const
Returns Lorentz vector.
Definition Particle.h:567
std::vector< Particle * > getDaughters() const
Returns a vector of pointers to daughter particles.
Definition Particle.cc:668
double getMomentumMagnitude() const
Returns momentum magnitude.
Definition Particle.h:589
const Particle * getDaughter(unsigned i) const
Returns a pointer to the i-th daughter particle.
Definition Particle.cc:662
static int EvtProcID()
Return ID of the current process.
static bool parallelProcessingUsed()
Returns true if multiple processes have been spawned, false in single-core mode.
This class stores additional information to every CDC/SVD/PXD hit stored in a RecoTrack.
CDCHit UsedCDCHit
Define, use of CDC hits as CDC hits (for symmetry).
EKLMAlignmentHit UsedEKLMHit
Define, use of EKLMHit2d as EKLM hits.
KLMHit2d UsedBKLMHit
Define, use of KLMHit2d as BKLM hits.
PXDCluster UsedPXDHit
Define, use of clusters or true hits for PXD.
SVDCluster UsedSVDHit
Define, use of clusters or true hits for SVD.
static genfit::Track & getGenfitTrack(RecoTrack &recoTrack)
Give access to the RecoTrack's genfit::Track.
Definition RecoTrack.cc:404
static genfit::AbsTrackRep * createOrReturnRKTrackRep(RecoTrack &recoTrack, int PDGcode)
Checks if a TrackRap for the PDG id of the RecoTrack (and its charge conjugate) does already exit and...
Definition RecoTrack.cc:409
This is the Reconstruction Event-Data Model Track.
Definition RecoTrack.h:79
genfit::AbsTrackRep * getCardinalRepresentation() const
Get a pointer to the cardinal track representation. You are not allowed to modify or delete it!
Definition RecoTrack.h:631
unsigned int getNumberOfCDCHits() const
Return the number of cdc hits.
Definition RecoTrack.h:427
const std::string & getStoreArrayNameOfRecoHitInformation() const
Name of the store array of the reco hit information.
Definition RecoTrack.h:747
const genfit::TrackPoint * getCreatedTrackPoint(const RecoHitInformation *recoHitInformation) const
Get a pointer to the TrackPoint that was created from this hit.
Definition RecoTrack.cc:230
const genfit::FitStatus * getTrackFitStatus(const genfit::AbsTrackRep *representation=nullptr) const
Return the track fit status for the given representation or for the cardinal one. You are not allowed...
Definition RecoTrack.h:621
RelationVector< TO > getRelationsTo(const std::string &name="", const std::string &namedRelation="") const
Get the relations that point from this object to another store array.
Rest frame of a particle.
virtual ROOT::Math::PxPyPzEVector getMomentum(const ROOT::Math::PxPyPzEVector &vector) const override
Get Lorentz vector in rest frame System.
bool isU() const
Is the coordinate u or v?
Definition SVDRecoHit.h:91
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
bool isValid() const
Check whether the array was registered.
Definition StoreArray.h:288
TClonesArray * getPtr() const
Raw access to the underlying TClonesArray.
Definition StoreArray.h:311
Type-safe access to single objects in the data store.
Definition StoreObjPtr.h:96
bool isValid() const
Check whether the object was created.
static int createCorrectPDGCodeForChargedStable(const Const::ChargedStable &particleType, const RecoTrack &recoTrack)
Helper function to multiply the PDG code of a charged stable with the charge of the reco track (if ne...
static const double GeV
Standard of [energy, momentum, mass].
Definition Unit.h:51
void writeConstraints(std::string txtFilename)
Write-out complete hierarchy to a text file.
Definition Manager.cc:169
void initialize(const std::vector< std::string > &components={}, const std::vector< EventMetaData > &timeSlices={})
Initialize the manager with given configuration (from MillepedeCollector)
Definition Manager.cc:52
void preCollect(const EventMetaData &emd)
Notice manager of a coming event (from MillepedeCollector)
Definition Manager.cc:98
static GlobalCalibrationManager & getInstance()
Get instance of the Manager auto& gcm = GlobalCalibrationManager::getInstance();.
Definition Manager.cc:27
Class for easier manipulation with global derivatives (and their labels)
static bool s_enablePXD
Enable PXD in hierarchy?
Definition GlobalParam.h:85
static bool s_enableSVD
Enable SVD in hierarchy?
Definition GlobalParam.h:87
static E_VXDHierarchyType s_hierarchyType
What type of hierarchy to use for VXD?
Definition GlobalParam.h:83
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:559
#define REG_MODULE(moduleName)
Register the given module (without 'Module' suffix) with the framework.
Definition Module.h:649
B2Vector3< double > B2Vector3D
typedef for common usage with double
Definition B2Vector3.h:516
double sqrt(double a)
sqrt for double
Definition beamHelpers.h:28
CoordinateMeasurementCreator< RecoHitInformation::UsedSVDHit, Const::SVD > SVDCoordinateMeasurementCreator
Hit to reco hit measurement creator for the SVD.
CoordinateMeasurementCreator< RecoHitInformation::UsedPXDHit, Const::PXD > PXDCoordinateMeasurementCreator
Hit to reco hit measurement creator for the PXD.
CoordinateMeasurementCreator< RecoHitInformation::UsedBKLMHit, Const::BKLM > BKLMCoordinateMeasurementCreator
Hit to reco hit measurement creator for the BKLM.
CoordinateMeasurementCreator< RecoHitInformation::UsedCDCHit, Const::CDC > CDCCoordinateMeasurementCreator
Needed for templating.
CoordinateMeasurementCreator< RecoHitInformation::UsedEKLMHit, Const::EKLM > EKLMCoordinateMeasurementCreator
Hit to reco hit measurement creator for the EKLM.
Abstract base class for different kinds of events.
STL namespace.