-
Notifications
You must be signed in to change notification settings - Fork 496
Expand file tree
/
Copy pathController.cxx
More file actions
1891 lines (1812 loc) · 64.8 KB
/
Controller.cxx
File metadata and controls
1891 lines (1812 loc) · 64.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019-2020 CERN and copyright holders of ALICE O2.
// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders.
// All rights not expressly granted are reserved.
//
// This software is distributed under the terms of the GNU General Public
// License v3 (GPL Version 3), copied verbatim in the file "COPYING".
//
// In applying this license CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.
/// @file Controller.h
/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch
/// @since 2021-02-01
/// @brief Steering class for the global alignment
#include "Align/Controller.h"
#include "Align/AlignConfig.h"
#include "Framework/Logger.h"
#include "Align/utils.h"
#include "Align/AlignmentPoint.h"
#include "Align/AlignableDetector.h"
#include "Align/AlignableVolume.h"
#include "Align/AlignableDetectorITS.h"
#include "Align/AlignableDetectorTRD.h"
#include "Align/AlignableDetectorTOF.h"
#include "Align/AlignableDetectorTPC.h"
#include "Align/EventVertex.h"
#include "Align/ResidualsControllerFast.h"
#include "Align/GeometricalConstraint.h"
#include "ReconstructionDataFormats/VtxTrackIndex.h"
#include "ReconstructionDataFormats/PrimaryVertex.h"
#include "DataFormatsGlobalTracking/RecoContainer.h"
#include "ReconstructionDataFormats/VtxTrackRef.h"
#include "TRDBase/TrackletTransformer.h"
#include "MathUtils/Utils.h"
#include <TMath.h>
#include <TString.h>
#include <TROOT.h>
#include <TSystem.h>
#include <TRandom.h>
#include <TH1F.h>
#include <TList.h>
#include <cstdio>
#include "GPUO2ExternalUser.h"
#include "DataFormatsTPC/WorkflowHelper.h"
#include <TGeoGlobalMagField.h>
#include "CommonUtils/NameConf.h"
#include "MathUtils/SymMatrixSolver.h"
#include "DataFormatsParameters/GRPObject.h"
#include "GPUParam.h"
#include "SimulationDataFormat/MCUtils.h"
#include "Steer/MCKinematicsReader.h"
#include "CommonUtils/TreeStreamRedirector.h"
#include <unordered_map>
using namespace TMath;
using namespace o2::align::utils;
using namespace o2::dataformats;
using namespace o2::globaltracking;
namespace o2
{
namespace align
{
using GIndex = o2::dataformats::VtxTrackIndex;
using PropagatorD = o2::base::PropagatorD;
using MatCorrType = PropagatorD::MatCorrType;
void Controller::ProcStat::print() const
{
const auto& stat0 = data[kInput];
LOGP(info, "StatSeen: Vtx: {:10} Tracks: {:10} TracksWVtx: {:10}", stat0[kVertices], stat0[kTracks], stat0[kTracksWithVertex]);
const auto& stat1 = data[kAccepted];
LOGP(info, "StatAcc : Vtx: {:10} Tracks: {:10} TracksWVtx: {:10}", stat1[kVertices], stat1[kTracks], stat1[kTracksWithVertex]);
}
const Char_t* Controller::sMPDataExt = ".mille";
const Char_t* Controller::sMPDataTxtExt = ".mille_txt";
const Char_t* Controller::sDetectorName[Controller::kNDetectors] = {"ITS", "TPC", "TRD", "TOF", "HMPID"}; //RSREM
//const int Controller::mgkSkipLayers[Controller::kNLrSkip] = {AliGeomManager::kPHOS1, AliGeomManager::kPHOS2,
// AliGeomManager::kMUON, AliGeomManager::kEMCAL}; TODO(milettri, shahoian): needs detector IDs previously stored in AliGeomManager
const int Controller::sSkipLayers[Controller::kNLrSkip] = {0, 0, 0, 0}; // TODO(milettri, shahoian): needs AliGeomManager - remove this line after fix.
//________________________________________________________________
Controller::Controller(DetID::mask_t detmask, GTrackID::mask_t trcmask, bool cosmic, bool useMC, int instID)
: mDetMask(detmask), mMPsrc(trcmask), mUseMC(useMC), mInstanceID(instID)
{
setCosmic(cosmic);
init();
}
//________________________________________________________________
Controller::~Controller()
{
// d-tor
closeMPRecOutput();
closeMilleOutput();
closeResidOutput();
//
}
//________________________________________________________________
void Controller::init()
{
if (mDetMask[DetID::ITS]) {
addDetector(new AlignableDetectorITS(this));
}
if (mDetMask[DetID::TRD]) {
addDetector(new AlignableDetectorTRD(this));
}
if (mDetMask[DetID::TPC]) {
addDetector(new AlignableDetectorTPC(this));
}
if (mDetMask[DetID::TOF]) {
addDetector(new AlignableDetectorTOF(this));
}
for (int src = GIndex::NSources; src--;) {
if (mMPsrc[src]) {
mTrackSources.push_back(src);
}
}
mVtxSens = std::make_unique<EventVertex>(this);
mVtxSens->setInternalID(1);
const auto& algConf = AlignConfig::Instance();
if (algConf.MPRecOutFraction > 0. || mInstanceID == 0) {
mMPRecOutFraction = std::abs(algConf.MPRecOutFraction);
}
if (algConf.controlFraction > 0. || mInstanceID == 0) {
mControlFraction = std::abs(algConf.controlFraction);
}
}
//________________________________________________________________
void Controller::process()
{
o2::steer::MCKinematicsReader mcReader;
if (mUseMC) {
if (!mcReader.initFromDigitContext("collisioncontext.root")) {
throw std::invalid_argument("initialization of MCKinematicsReader failed");
}
}
auto timerStart = std::chrono::system_clock::now();
int nVtx = 0, nVtxAcc = 0, nTrc = 0, nTrcAcc = 0;
for (auto id = DetID::First; id <= DetID::Last; id++) {
auto* det = getDetector(id);
if (det) {
det->prepareDetectorData(); // in case the detector needs to preprocess the RecoContainer data
}
}
auto primVertices = mRecoData->getPrimaryVertices();
auto primVer2TRefs = mRecoData->getPrimaryVertexMatchedTrackRefs();
auto primVerGIs = mRecoData->getPrimaryVertexMatchedTracks();
const auto& algConf = AlignConfig::Instance();
// process vertices with contributor tracks
std::unordered_map<GIndex, bool> ambigTable;
int nvRefs = primVer2TRefs.size();
bool fieldON = std::abs(PropagatorD::Instance()->getNominalBz()) > 0.1;
for (int ivref = 0; ivref < nvRefs; ivref++) {
const o2::dataformats::PrimaryVertex* vtx = (ivref < nvRefs - 1) ? &primVertices[ivref] : nullptr;
bool useVertexConstrain = false;
if (vtx) {
auto nContrib = vtx->getNContributors();
// check cov matrix since data reconstructed with < 6797a257f5ab8ffaec32d56dddb0a321939bdf1c may have negative errors
if (vtx->getSigmaX2() < 0. || vtx->getSigmaY2() < 0. || vtx->getSigmaZ2() < 0.) {
continue;
}
useVertexConstrain = nContrib >= algConf.vtxMinCont && nContrib <= algConf.vtxMaxCont;
mStat.data[ProcStat::kInput][ProcStat::kVertices]++;
}
auto& trackRef = primVer2TRefs[ivref];
if (algConf.verbose > 1) {
LOGP(info, "processing vtref {} of {} with {} tracks, {}", ivref, nvRefs, trackRef.getEntries(), vtx ? vtx->asString() : std::string{});
}
nVtx++;
bool newVtx = true;
for (int src : mTrackSources) {
if ((GIndex::getSourceDetectorsMask(src) & mDetMask).none()) { // do we need this source?
continue;
}
int start = trackRef.getFirstEntryOfSource(src), end = start + trackRef.getEntriesOfSource(src);
for (int ti = start; ti < end; ti++) {
auto trackIndex = primVerGIs[ti];
mAlgTrack->setCurrentTrackID(trackIndex);
bool tpcIn = false;
if (trackIndex.isAmbiguous()) {
auto& ambSeen = ambigTable[trackIndex];
if (ambSeen) { // processed
continue;
}
ambSeen = true;
}
mStat.data[ProcStat::kInput][ProcStat::kTracks]++;
if (vtx) {
mStat.data[ProcStat::kInput][ProcStat::kTracksWithVertex]++;
}
int npnt = 0;
auto contributorsGID = mRecoData->getSingleDetectorRefs(trackIndex);
std::string trComb;
for (int ig = 0; ig < GIndex::NSources; ig++) {
if (contributorsGID[ig].isIndexSet()) {
trComb += " " + contributorsGID[ig].asString();
}
}
if (algConf.verbose > 1) {
LOG(info) << "processing track " << trackIndex.asString() << " contributors: " << trComb;
}
resetForNextTrack();
nTrc++;
// RS const auto& trcOut = mRecoData->getTrackParamOut(trackIndex);
auto trcOut = mRecoData->getTrackParamOut(trackIndex);
const auto& trcIn = mRecoData->getTrackParam(trackIndex);
// check detectors contributions
AlignableDetector* det = nullptr;
int ndet = 0, npntDet = 0;
if ((det = getDetector(DetID::ITS))) {
if (contributorsGID[GIndex::ITS].isIndexSet() && (npntDet = det->processPoints(contributorsGID[GIndex::ITS], algConf.minITSClusters, false)) > 0) {
npnt += npntDet;
ndet++;
} else if (mAllowAfterburnerTracks && contributorsGID[GIndex::ITSAB].isIndexSet() && (npntDet = det->processPoints(contributorsGID[GIndex::ITSAB], 2, false)) > 0) {
npnt += npntDet;
ndet++;
} else {
continue;
}
}
if ((det = getDetector(DetID::TPC)) && contributorsGID[GIndex::TPC].isIndexSet()) {
float t0 = 0, t0err = 0;
mRecoData->getTrackTime(trackIndex, t0, t0err);
((AlignableDetectorTPC*)det)->setTrackTimeStamp(t0);
npntDet = det->processPoints(contributorsGID[GIndex::TPC], algConf.minTPCClusters, false);
if (npntDet > 0) {
npnt += npntDet;
ndet++;
tpcIn = true;
}
}
if ((det = getDetector(DetID::TRD)) && contributorsGID[GIndex::TRD].isIndexSet() && (npntDet = det->processPoints(contributorsGID[GIndex::TRD], algConf.minTRDTracklets, false)) > 0) {
npnt += npntDet;
ndet++;
}
if ((det = getDetector(DetID::TOF)) && contributorsGID[GIndex::TOF].isIndexSet() && (npntDet = det->processPoints(contributorsGID[GIndex::TOF], algConf.minTOFClusters, false)) > 0) {
npnt += npntDet;
ndet++;
}
// other detectors
if (algConf.verbose > 1) {
LOGP(info, "processing track {} {} of vtref {}, Ndets:{}, Npoints: {}, use vertex: {} | Kin: {} Kout: {}", ti, trackIndex.asString(), ivref, ndet, npnt, useVertexConstrain && trackIndex.isPVContributor(), trcIn.asString(), trcOut.asString());
}
if (ndet < algConf.minDetectors || (tpcIn && ndet == 1)) { // we don't want TPC only track
continue;
}
if (npnt < algConf.minPointTotal) {
if (algConf.verbose > 0) {
LOGP(info, "too few points {} < {}", npnt, algConf.minPointTotal);
}
continue;
}
bool vtxCont = false;
if (trackIndex.isPVContributor() && useVertexConstrain) {
mAlgTrack->copyFrom(trcIn); // copy kinematices of inner track just for propagation to the vertex
if (addVertexConstraint(*vtx)) {
mAlgTrack->setRefPoint(mRefPoint.get()); // set vertex as a reference point
vtxCont = true;
}
}
mAlgTrack->copyFrom(trcOut); // copy kinematices of outer track as the refit will be done inward
mAlgTrack->setFieldON(fieldON);
mAlgTrack->sortPoints();
int pntMeas = mAlgTrack->getInnerPointID() - 1;
if (pntMeas < 0) { // this should not happen
mAlgTrack->Print("p meas");
LOG(error) << "AliAlgTrack->GetInnerPointID() cannot be 0";
}
if (!mAlgTrack->iniFit()) {
if (algConf.verbose > 0) {
LOGP(warn, "iniFit failed");
}
continue;
}
// compare refitted and original track
if (mDebugOutputLevel) {
trackParam_t trcAlgRef(*mAlgTrack.get());
std::array<double, 5> dpar{};
std::array<double, 15> dcov{};
for (int i = 0; i < 5; i++) {
dpar[i] = trcIn.getParam(i);
}
for (int i = 0; i < 15; i++) {
dcov[i] = trcIn.getCov()[i];
}
trackParam_t trcOrig(trcIn.getX(), trcIn.getAlpha(), dpar, dcov, trcIn.getCharge());
if (PropagatorD::Instance()->propagateToAlphaX(trcOrig, trcAlgRef.getAlpha(), trcAlgRef.getX(), true)) {
(*mDBGOut) << "trcomp"
<< "orig=" << trcOrig << "fit=" << trcAlgRef << "\n";
}
}
// RS: this is to substitute the refitter track by MC truth, just for debugging
/*
if (mUseMC) {
auto lbl = mRecoData->getTrackMCLabel(trackIndex);
if (lbl.isValid()) {
o2::MCTrack mcTrack = *mcReader.getTrack(lbl);
std::array<float,3> xyz{(float)mcTrack.GetStartVertexCoordinatesX(),(float)mcTrack.GetStartVertexCoordinatesY(),(float)mcTrack.GetStartVertexCoordinatesZ()},
pxyz{(float)mcTrack.GetStartVertexMomentumX(),(float)mcTrack.GetStartVertexMomentumY(),(float)mcTrack.GetStartVertexMomentumZ()};
std::array<float,21> cv21{10., 0.,10., 0.,0.,10., 0.,0.,0.,1., 0.,0.,0.,0.,1., 0.,0.,0.,0.,0.,1.};
trcOut.set(xyz, pxyz, cv21, trcOut.getSign(), false);
mAlgTrack->copyFrom(trcOut);
}
}
*/
if (!mAlgTrack->processMaterials()) {
if (algConf.verbose > 0) {
LOGP(warn, "processMaterials failed");
}
continue;
}
mAlgTrack->defineDOFs();
if (!mAlgTrack->calcResidDeriv()) {
if (algConf.verbose > 0) {
LOGP(warn, "calcResidDeriv failed");
}
continue;
}
if (mDebugOutputLevel && mAlgTrackDbg.setTrackParam(mAlgTrack.get())) {
mAlgTrackDbg.mGID = trackIndex;
(*mDBGOut) << "algtrack"
<< "runNumber=" << mTimingInfo.runNumber
<< "tfID=" << mTimingInfo.tfCounter
<< "orbit=" << mTimingInfo.firstTForbit
<< "bz=" << PropagatorD::Instance()->getNominalBz()
<< "t=" << mAlgTrackDbg << "\n";
}
if (mUseMC && mDebugOutputLevel > 1) {
auto lbl = mRecoData->getTrackMCLabel(trackIndex);
if (lbl.isValid()) {
std::vector<float> pntX, pntY, pntZ, trcX, trcY, trcZ, prpX, prpY, prpZ, alpha, xsens, pntXTF, pntYTF, pntZTF, resY, resZ;
std::vector<int> detid, volid;
o2::MCTrack mcTrack = *mcReader.getTrack(lbl);
trackParam_t recTrack{*mAlgTrack};
for (int ip = 0; ip < mAlgTrack->getNPoints(); ip++) {
double tmp[3], tmpg[3];
auto* pnt = mAlgTrack->getPoint(ip);
auto* sens = pnt->getSensor();
detid.emplace_back(pnt->getDetID());
volid.emplace_back(pnt->getVolID());
TGeoHMatrix t2g;
sens->getMatrixT2G(t2g);
t2g.LocalToMaster(pnt->getXYZTracking(), tmpg);
pntX.emplace_back(tmpg[0]);
pntY.emplace_back(tmpg[1]);
pntZ.emplace_back(tmpg[2]);
double xyz[3]{pnt->getXTracking(), pnt->getYTracking(), pnt->getZTracking()};
xyz[1] += mAlgTrack->getResidual(0, ip);
xyz[2] += mAlgTrack->getResidual(1, ip);
t2g.LocalToMaster(xyz, tmpg);
trcX.emplace_back(tmpg[0]);
trcY.emplace_back(tmpg[1]);
trcZ.emplace_back(tmpg[2]);
pntXTF.emplace_back(pnt->getXTracking());
pntYTF.emplace_back(pnt->getYTracking());
pntZTF.emplace_back(pnt->getZTracking());
resY.emplace_back(mAlgTrack->getResidual(0, ip));
resZ.emplace_back(mAlgTrack->getResidual(1, ip));
alpha.emplace_back(pnt->getAlphaSens());
xsens.emplace_back(pnt->getXSens());
}
(*mDBGOut) << "mccomp"
<< "mcTr=" << mcTrack << "recTr=" << recTrack << "gid=" << trackIndex << "lbl=" << lbl << "vtxConst=" << vtxCont
<< "pntX=" << pntX << "pntY=" << pntY << "pntZ=" << pntZ
<< "trcX=" << trcX << "trcY=" << trcY << "trcZ=" << trcZ
<< "alp=" << alpha << "xsens=" << xsens
<< "pntXTF=" << pntXTF << "pntYTF=" << pntYTF << "pntZTF=" << pntZTF
<< "resY=" << resY << "resZ=" << resZ
<< "detid=" << detid << "volid=" << volid << "\n";
}
}
mStat.data[ProcStat::kAccepted][ProcStat::kTracks]++;
if (vtxCont) {
mStat.data[ProcStat::kAccepted][ProcStat::kTracksWithVertex]++;
}
nTrcAcc++;
if (newVtx) {
newVtx = false;
mStat.data[ProcStat::kAccepted][ProcStat::kVertices]++;
nVtxAcc++;
}
storeProcessedTrack(trackIndex);
}
}
}
auto timerEnd = std::chrono::system_clock::now();
std::chrono::duration<float, std::milli> duration = timerEnd - timerStart;
LOGP(info, "Processed TF {}: {} vertices ({} used), {} tracks ({} used) in {} ms", mNTF, nVtx, nVtxAcc, nTrc, nTrcAcc, duration.count());
mNTF++;
}
//________________________________________________________________
void Controller::processCosmic()
{
auto timerStart = std::chrono::system_clock::now();
const auto tracks = mRecoData->getCosmicTracks();
if (!tracks.size()) {
LOGP(info, "Skipping TF {}: No cosmic tracks", mNTF);
mNTF++;
return;
}
int nTrc = 0, nTrcAcc = 0;
for (auto id = DetID::First; id <= DetID::Last; id++) {
auto* det = getDetector(id);
if (det) {
det->prepareDetectorData(); // in case the detector needs to preprocess the RecoContainer data
}
}
const auto& algConf = AlignConfig::Instance();
bool fieldON = std::abs(PropagatorD::Instance()->getNominalBz()) > 0.1;
for (const auto& track : tracks) {
resetForNextTrack();
nTrc++;
mStat.data[ProcStat::kInput][ProcStat::kCosmic]++;
std::array<GTrackID, GTrackID::NSources> contributorsGID[2] = {mRecoData->getSingleDetectorRefs(track.getRefBottom()), mRecoData->getSingleDetectorRefs(track.getRefTop())};
bool hasTRD = false, hasITS = false, hasTPC = false, hasTOF = false;
if (contributorsGID[0][GTrackID::TRD].isIndexSet() || contributorsGID[1][GTrackID::TRD].isIndexSet()) {
hasTRD = true;
}
if (contributorsGID[0][GTrackID::TOF].isIndexSet() || contributorsGID[1][GTrackID::TOF].isIndexSet()) {
hasTOF = true;
}
if (contributorsGID[0][GTrackID::TPC].isIndexSet() || contributorsGID[1][GTrackID::TPC].isIndexSet()) {
hasTPC = true;
}
if (contributorsGID[0][GTrackID::ITS].isIndexSet() || contributorsGID[1][GTrackID::ITS].isIndexSet()) {
hasITS = true;
}
// check detectors contributions
AlignableDetector* det = nullptr;
int ndet = 0, npnt = 0;
bool accTrack = true;
bool tpcIn = false;
if ((det = getDetector(DetID::ITS))) {
int npntDet = 0;
for (int ibt = 0; ibt < 2; ibt++) {
int npntDetBT = 0;
mAlgTrack->setCurrentTrackID(ibt ? track.getRefBottom() : track.getRefTop());
if (contributorsGID[ibt][GIndex::ITS].isIndexSet() && (npntDetBT = det->processPoints(contributorsGID[ibt][GIndex::ITS], algConf.minITSClustersCosmLeg, ibt)) < 0) {
accTrack = false;
break;
}
npntDet += npntDetBT;
}
if (!accTrack || npntDet < algConf.minITSClustersCosm) {
continue;
}
if (npntDet) {
ndet++;
npnt += npntDet;
}
}
if ((det = getDetector(DetID::TPC))) {
int npntDet = 0;
((AlignableDetectorTPC*)det)->setTrackTimeStamp(track.getTimeMUS().getTimeStamp());
for (int ibt = 0; ibt < 2; ibt++) {
int npntDetBT = 0;
mAlgTrack->setCurrentTrackID(ibt ? track.getRefBottom() : track.getRefTop());
if (contributorsGID[ibt][GIndex::TPC].isIndexSet() && (npntDetBT = det->processPoints(contributorsGID[ibt][GIndex::TPC], algConf.minTPCClustersCosmLeg, ibt)) < 0) {
accTrack = false;
break;
}
npntDet += npntDetBT;
}
if (!accTrack || npntDet < algConf.minTPCClustersCosm) {
continue;
}
if (npntDet) {
ndet++;
npnt += npntDet;
tpcIn = true;
}
}
if ((det = getDetector(DetID::TRD))) {
int npntDet = 0;
for (int ibt = 0; ibt < 2; ibt++) {
int npntDetBT = 0;
mAlgTrack->setCurrentTrackID(ibt ? track.getRefBottom() : track.getRefTop());
if (contributorsGID[ibt][GIndex::TRD].isIndexSet() && (npntDetBT = det->processPoints(contributorsGID[ibt][GIndex::TRD], algConf.minTRDTrackletsCosmLeg, ibt)) < 0) {
accTrack = false;
break;
}
npntDet += npntDetBT;
}
if (!accTrack || npntDet < algConf.minTRDTrackletsCosm) {
continue;
}
if (npntDet) {
ndet++;
npnt += npntDet;
}
}
if ((det = getDetector(DetID::TOF))) {
int npntDet = 0;
for (int ibt = 0; ibt < 2; ibt++) {
int npntDetBT = 0;
mAlgTrack->setCurrentTrackID(ibt ? track.getRefBottom() : track.getRefTop());
if (contributorsGID[ibt][GIndex::TOF].isIndexSet() && (npntDetBT = det->processPoints(contributorsGID[ibt][GIndex::TOF], algConf.minTOFClustersCosmLeg, ibt)) < 0) {
accTrack = false;
break;
}
npntDet += npntDetBT;
}
if (!accTrack || npntDet < algConf.minTOFClustersCosm) {
continue;
}
if (npntDet) {
ndet++;
npnt += npntDet;
}
}
if (algConf.verbose > 1) {
LOGP(info, "processing cosmic track B-Leg:{} T-Leg:{}, Ndets:{}, Npoints: {}", track.getRefBottom().asString(), track.getRefTop().asString(), ndet, npnt);
}
if (ndet < algConf.minDetectorsCosm /* || (tpcIn && ndet == 1)*/) {
continue;
}
if (npnt < algConf.minPointTotalCosm) {
if (algConf.verbose > 0) {
LOGP(info, "too few points {} < {}", npnt, algConf.minPointTotalCosm);
}
continue;
}
mAlgTrack->setCosmic(true);
mAlgTrack->copyFrom(mRecoData->getTrackParamOut(track.getRefBottom())); // copy kinematices of outer track as the refit will be done inward
mAlgTrack->setFieldON(fieldON);
mAlgTrack->sortPoints();
if (!mAlgTrack->iniFit()) {
if (algConf.verbose > 0) {
LOGP(warn, "iniFit failed");
}
continue;
}
if (!mAlgTrack->processMaterials()) {
if (algConf.verbose > 0) {
LOGP(warn, "processMaterials failed");
}
continue;
}
mAlgTrack->defineDOFs();
if (!mAlgTrack->calcResidDeriv()) {
if (algConf.verbose > 0) {
LOGP(warn, "calcResidDeriv failed");
}
continue;
}
if (mDebugOutputLevel && mAlgTrackDbg.setTrackParam(mAlgTrack.get())) {
mAlgTrackDbg.mGID = track.getRefBottom();
mAlgTrackDbg.mGIDCosmUp = track.getRefTop();
(*mDBGOut) << "algtrack"
<< "runNumber=" << mTimingInfo.runNumber
<< "tfID=" << mTimingInfo.tfCounter
<< "orbit=" << mTimingInfo.firstTForbit
<< "bz=" << PropagatorD::Instance()->getNominalBz()
<< "t=" << mAlgTrackDbg << "\n";
}
storeProcessedTrack();
mStat.data[ProcStat::kAccepted][ProcStat::kCosmic]++;
nTrcAcc++;
}
auto timerEnd = std::chrono::system_clock::now();
std::chrono::duration<float, std::milli> duration = timerEnd - timerStart;
LOGP(info, "Processed cosmic TF {}: {} tracks ({} used) in {} ms", mNTF, nTrc, nTrcAcc, duration.count());
mNTF++;
}
//________________________________________________________________
void Controller::initDetectors()
{
// init all detectors geometry
//
if (getInitGeomDone()) {
return;
}
//
mAlgTrack = std::make_unique<AlignmentTrack>();
mRefPoint = std::make_unique<AlignmentPoint>();
//
int dofCnt = 0;
// special fake sensor for vertex constraint point
// it has special T2L matrix adjusted for each track, no need to init it here
mVtxSens->prepareMatrixL2G();
mVtxSens->prepareMatrixL2GIdeal();
dofCnt += mVtxSens->getNDOFs();
//
for (auto id = DetID::First; id <= DetID::Last; id++) {
auto* det = getDetector(id);
if (det) {
dofCnt += det->initGeom();
}
}
if (!dofCnt) {
LOG(fatal) << "No DOFs found";
}
//
//
for (auto id = DetID::First; id <= DetID::Last; id++) {
auto* det = getDetector(id);
if (!det || det->isDisabled()) {
continue;
}
det->cacheReferenceCCDB();
}
//
assignDOFs();
LOG(info) << "Booked " << dofCnt << " global parameters";
//
setInitGeomDone();
//
}
//________________________________________________________________
void Controller::initDOFs()
{
// scan all free global parameters, link detectors to array of params
//
if (getInitDOFsDone()) {
LOG(info) << "initDOFs was already done, just reassigning " << getNDOFs() << "DOFs arrays/labels";
assignDOFs();
return;
}
const auto& conf = AlignConfig::Instance();
mNDOFs = 0;
int ndfAct = 0;
assignDOFs();
int nact = 0;
mVtxSens->initDOFs();
for (auto id = DetID::First; id <= DetID::Last; id++) {
AlignableDetector* det = getDetector(id);
if (det && !det->isDisabled()) {
det->initDOFs();
nact++;
ndfAct += det->getNDOFs();
}
}
for (int i = 0; i < NTrackTypes; i++) {
if (nact < conf.minDetAcc[i]) {
LOG(fatal) << nact << " detectors are active, while " << conf.minDetAcc[i] << " in track are asked";
}
}
LOG(info) << mNDOFs << " global parameters " << mNDet << " detectors, " << ndfAct << " in " << nact << " active detectors";
addAutoConstraints();
setInitDOFsDone();
}
//________________________________________________________________
void Controller::assignDOFs()
{
// add parameters/labels arrays to volumes. If the Controller is read from the file, this method need
// to be called (of initDOFs should be called)
//
int ndfOld = -1;
if (mNDOFs > 0) {
ndfOld = mNDOFs;
}
mNDOFs = 0;
//
// reserve
int ndofTOT = mVtxSens->getNDOFs();
for (auto id = DetID::First; id <= DetID::Last; id++) {
AlignableDetector* det = getDetector(id);
if (!det) {
continue;
}
ndofTOT += det->getNDOFs();
}
mGloParVal.clear();
mGloParErr.clear();
mGloParLab.clear();
mLbl2ID.clear();
mGloParVal.reserve(ndofTOT);
mGloParErr.reserve(ndofTOT);
mGloParLab.reserve(ndofTOT);
mVtxSens->assignDOFs();
for (auto id = DetID::First; id <= DetID::Last; id++) {
AlignableDetector* det = getDetector(id);
if (!det) {
continue;
}
det->assignDOFs();
}
LOG(info) << "Assigned parameters/labels arrays for " << mNDOFs << " DOFs";
if (ndfOld > 0 && ndfOld != mNDOFs) {
LOG(error) << "Recalculated NDOFs=" << mNDOFs << " not equal to saved NDOFs=" << ndfOld;
}
// build Lbl -> parID table
for (int i = 0; i < ndofTOT; i++) {
int& id = mLbl2ID[mGloParLab[i]];
if (id != 0) {
LOGP(fatal, "parameters {} and {} share the same label {}", id - 1, i, mGloParLab[i]);
}
id = i + 1;
}
//
}
//_________________________________________________________
void Controller::addDetector(AlignableDetector* det)
{
// add detector constructed externally to alignment framework
mDetectors[det->getDetID()].reset(det);
mNDet++;
}
//_________________________________________________________
bool Controller::checkDetectorPattern(DetID::mask_t patt) const
{
//validate detector pattern
return ((patt & mObligatoryDetPattern[mTracksType]) == mObligatoryDetPattern[mTracksType]) &&
patt.count() >= AlignConfig::Instance().minDetAcc[mTracksType];
}
//_________________________________________________________
bool Controller::checkDetectorPoints(const int* npsel) const
{
//validate detectors pattern according to number of selected points
int ndOK = 0;
for (auto id = DetID::First; id <= DetID::Last; id++) {
AlignableDetector* det = getDetector(id);
if (!det || det->isDisabled(mTracksType)) {
continue;
}
if (npsel[id] < det->getNPointsSel(mTracksType)) {
if (det->isObligatory(mTracksType)) {
return false;
}
continue;
}
ndOK++;
}
return ndOK >= AlignConfig::Instance().minDetAcc[mTracksType];
}
//_________________________________________________________
bool Controller::storeProcessedTrack(o2::dataformats::GlobalTrackID tid)
{
// write alignment track
bool res = true;
const auto& conf = AlignConfig::Instance();
if (conf.MilleOut) {
res &= fillMilleData();
}
float rnd = gRandom->Rndm();
if (mMPRecOutFraction > rnd) {
res &= fillMPRecData(tid);
}
if ((mControlFraction > rnd) && mAlgTrack->testLocalSolution()) {
res &= fillControlData(tid);
}
//
if (!res) {
LOGP(error, "storeProcessedTrack failed");
}
return res;
}
//_________________________________________________________
bool Controller::fillMilleData()
{
// store MP2 data in Mille format
if (!mMille) {
const auto& conf = AlignConfig::Instance();
mMilleFileName = fmt::format("{}_{:08d}_{:010d}{}", AlignConfig::Instance().mpDatFileName, mTimingInfo.runNumber, mTimingInfo.tfCounter, conf.MilleOutBin ? sMPDataExt : sMPDataTxtExt);
mMille = std::make_unique<Mille>(mMilleFileName.c_str(), conf.MilleOutBin);
}
if (!mAlgTrack->getDerivDone()) {
LOG(error) << "Track derivatives are not yet evaluated";
return false;
}
int np = mAlgTrack->getNPoints(), nDGloTot = 0; // total number global derivatives stored
int nParETP = mAlgTrack->getNLocExtPar(); // numnber of local parameters for reference track param
int nVarLoc = mAlgTrack->getNLocPar(); // number of local degrees of freedom in the track
//
const int* gloParID = mAlgTrack->getGloParID(); // IDs of global DOFs this track depends on
for (int ip = 0; ip < np; ip++) {
AlignmentPoint* pnt = mAlgTrack->getPoint(ip);
if (pnt->containsMeasurement()) {
int gloOffs = pnt->getDGloOffs(); // 1st entry of global derivatives for this point
int nDGlo = pnt->getNGloDOFs(); // number of global derivatives (number of DOFs it depends on)
if (!pnt->isStatOK()) {
pnt->incrementStat();
}
int milleIBufferG[nDGlo];
float milleDBufferG[nDGlo];
float milleDBufferL[nVarLoc];
std::memset(milleIBufferG, 0, sizeof(int) * nDGlo);
std::memset(milleDBufferG, 0, sizeof(float) * nDGlo);
std::memset(milleDBufferL, 0, sizeof(float) * nVarLoc);
// local der. array cannot be 0-suppressed by Mille construction, need to reset all to 0
for (int idim = 0; idim < 2; idim++) { // 2 dimensional orthogonal measurement
const double* deriv = mAlgTrack->getDResDLoc(idim, ip); // array of Dresidual/Dparams_loc
// derivatives over reference track parameters
for (int j = 0; j < nParETP; j++) {
milleDBufferL[j] = isZeroAbs(deriv[j]) ? 0. : deriv[j];
}
//
// point may depend on material variables within these limits
for (int j = pnt->getMinLocVarID(); j < pnt->getMaxLocVarID(); j++) {
milleDBufferL[j] = isZeroAbs(deriv[j]) ? 0. : deriv[j];
}
// derivatives over global params: this array can be 0-suppressed, no need to reset
int nGlo = 0;
deriv = mAlgTrack->getDResDGlo(idim, gloOffs);
const int* gloIDP(gloParID + gloOffs);
for (int j = 0; j < nDGlo; j++) {
milleDBufferG[nGlo] = isZeroAbs(deriv[j]) ? 0. : deriv[j]; // value of derivative
milleIBufferG[nGlo++] = getGloParLab(gloIDP[j]); // global DOF ID + 1 (Millepede needs positive labels)
}
mMille->mille(nVarLoc, milleDBufferL, nGlo, milleDBufferG, milleIBufferG, mAlgTrack->getResidual(idim, ip), Sqrt(pnt->getErrDiag(idim)));
nDGloTot += nGlo;
}
}
if (pnt->containsMaterial()) { // material point can add 4 or 5 otrhogonal pseudo-measurements
int nmatpar = pnt->getNMatPar(); // residuals (correction expectation value)
// const float* expMatCorr = pnt->getMatCorrExp(); // expected corrections (diagonalized)
const float* expMatCov = pnt->getMatCorrCov(); // their diagonalized error matrix
int offs = pnt->getMaxLocVarID() - nmatpar; // start of material variables
// here all derivatives are 1 = dx/dx
float milleDBufferL[nVarLoc];
std::memset(milleDBufferL, 0, sizeof(float) * nVarLoc);
for (int j = 0; j < nmatpar; j++) { // mat. "measurements" don't depend on global params
int j1 = j + offs;
milleDBufferL[j1] = 1.0; // only 1 non-0 derivative
// mMille->mille(nVarLoc,milleDBufferL,0, nullptr, nullptr, expMatCorr[j], Sqrt(expMatCov[j]));
// expectation for MS effect is 0
mMille->mille(nVarLoc, milleDBufferL, 0, nullptr, nullptr, 0, Sqrt(expMatCov[j]));
milleDBufferL[j1] = 0.0; // reset buffer
}
} // material "measurement"
} // loop over points
//
if (!nDGloTot) {
LOG(info) << "Track does not depend on free global parameters, discard";
mMille->clear();
return false;
}
mMille->finalise(); // store the record
return true;
}
//_________________________________________________________
bool Controller::fillMPRecData(o2::dataformats::GlobalTrackID tid)
{
// store MP2 in MPRecord format
if (!mMPRecFile) {
initMPRecOutput();
}
mMPRecord.clear();
if (!mMPRecord.fillTrack(*mAlgTrack.get(), mGloParLab)) {
return false;
}
mMPRecord.setRun(mRunNumber);
mMPRecord.setFirstTFOrbit(mTimingInfo.firstTForbit);
mMPRecord.setTrackID(tid);
mMPRecTree->Fill();
return true;
}
//_________________________________________________________
bool Controller::fillControlData(o2::dataformats::GlobalTrackID tid)
{
// store control residuals
if (!mResidFile) {
initResidOutput();
}
int nps, np = mAlgTrack->getNPoints();
nps = (!mRefPoint->containsMeasurement()) ? np - 1 : np; // ref point is dummy?
if (nps < 0) {
return true;
}
mCResid.clear();
if (!mCResid.fillTrack(*mAlgTrack.get(), AlignConfig::Instance().KalmanResid)) {
return false;
}
mCResid.setRun(mRunNumber);
mCResid.setFirstTFOrbit(mTimingInfo.firstTForbit);
mCResid.setBz(o2::base::PropagatorD::Instance()->getNominalBz());
mCResid.setTrackID(tid);
// if (isCosmic()) {
// mCResid.setInvTrackID(tid);
// }
mResidTree->Fill();
return true;
}
//_________________________________________________________
void Controller::setTimingInfo(const o2::framework::TimingInfo& ti)
{
mTimingInfo = ti;
LOGP(info, "TIMING {} {}", ti.runNumber, ti.creation);
if (ti.runNumber != mRunNumber) {
mRunNumber = ti.runNumber;
}
}
//____________________________________________
void Controller::Print(const Option_t* opt) const
{
// print info
TString opts = opt;
opts.ToLower();
printf("%5d DOFs in %d detectors\n", mNDOFs, mNDet);
if (getMPAlignDone()) {
printf("ALIGNMENT FROM MILLEPEDE SOLUTION IS APPLIED\n");
}
//
for (auto id = DetID::First; id <= DetID::Last; id++) {
AlignableDetector* det = getDetector(id);
if (!det) {
continue;
}
det->Print(opt);
}
if (!opts.IsNull()) {
printf("\nSpecial sensor for Vertex Constraint\n");
mVtxSens->Print(opt);
}
//
if (mRefRunNumber >= 0) {
printf("(%d)", mRefRunNumber);
}
AlignConfig::Instance().printKeyValues();
//
if (opts.Contains("stat")) {
printStatistics();
}
}
//________________________________________________________
void Controller::printStatistics() const
{
// print processing stat
mStat.print();
}
//________________________________________________________
void Controller::resetForNextTrack()
{
// reset detectors for next track
mRefPoint->clear();
mAlgTrack->Clear();
for (auto id = DetID::First; id <= DetID::Last; id++) {
AlignableDetector* det = getDetector(id);
if (det) {
det->reset();
}
}
}
//____________________________________________
bool Controller::testLocalSolution()
{
// test track local solution
int npnt = mAlgTrack->getNPoints(), nlocpar = mAlgTrack->getNLocPar();
double mat[nlocpar][nlocpar], rhs[nlocpar];
std::memset(mat, 0, sizeof(double) * nlocpar * nlocpar);
std::memset(rhs, 0, sizeof(double) * nlocpar);
for (int ip = npnt; ip--;) {
AlignmentPoint* pnt = mAlgTrack->getPoint(ip);
if (pnt->containsMeasurement()) {
for (int idim = 2; idim--;) { // each point has 2 position residuals
double resid = mAlgTrack->getResidual(idim, ip), sg2inv = 1. / pnt->getErrDiag(idim); // residual and its inv. error
auto deriv = mAlgTrack->getDResDLoc(idim, ip); // array of Dresidual/Dparams
for (int parI = 0; parI < nlocpar; parI++) {
rhs[parI] -= deriv[parI] * resid * sg2inv;
for (int parJ = parI; parJ < nlocpar; parJ++) {
mat[parI][parJ] += deriv[parI] * deriv[parJ] * sg2inv;
}
}
} // loop over 2 orthogonal measurements at the point
} // derivarives at measured points
// if the point contains material, consider its expected kinks, eloss as measurements
if (pnt->containsMaterial()) { // at least 4 parameters: 2 spatial + 2 angular kinks with 0 expectaction
int npm = pnt->getNMatPar();
// const float* expMatCorr = pnt->getMatCorrExp(); // expected correction (diagonalized) // RS??