-
Notifications
You must be signed in to change notification settings - Fork 496
Expand file tree
/
Copy pathAlignmentTrack.cxx
More file actions
1587 lines (1537 loc) · 61.5 KB
/
AlignmentTrack.cxx
File metadata and controls
1587 lines (1537 loc) · 61.5 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 AlignmentTrack.h
/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch
/// @since 2021-02-01
/// @brief Track model for the alignment
#include <cstdio>
#include "Align/AlignmentTrack.h"
#include "Framework/Logger.h"
#include "Align/AlignableSensor.h"
#include "Align/AlignableVolume.h"
#include "Align/AlignableDetector.h"
#include "Align/AlignConfig.h"
#include "Align/utils.h"
#include <TMatrixD.h>
#include <TVectorD.h>
#include <TMatrixDSymEigen.h>
#include "MathUtils/SymMatrixSolver.h"
#include "MathUtils/Utils.h"
#define DEBUG 4
using namespace o2::align::utils;
using namespace o2::base;
using namespace TMath;
namespace o2
{
namespace align
{
// RS: this is not good: we define constants outside the class, but it is to
// bypass the CINT limitations on static arrays initializations
const int kRichardsonOrd = 1; // Order of Richardson extrapolation for derivative (min=1)
const int kRichardsonN = kRichardsonOrd + 1; // N of 2-point symmetric derivatives needed for requested order
const int kNRDClones = kRichardsonN * 2; // number of variations for derivative of requested order
//____________________________________________________________________________
void AlignmentTrack::Clear(Option_t*)
{
// reset the track
TObject::Clear();
ResetBit(0xffffffff);
mPoints.clear();
mDetPoints.clear();
mChi2 = mChi2CosmUp = mChi2CosmDn = mChi2Ini = 0;
mNDF = 0;
mInnerPointID = -1;
mNeedInv[0] = mNeedInv[1] = false;
mNLocPar = mNLocExtPar = mNGloPar = 0;
//
}
//____________________________________________________________________________
void AlignmentTrack::defineDOFs()
{
// define varied DOF's (local parameters) for the track:
// 1) kinematic params (5 or 4 depending on Bfield)
// 2) mult. scattering angles (2)
// 3) if requested by point: energy loss
//
mNLocPar = mNLocExtPar = getFieldON() ? kNKinParBON : kNKinParBOFF;
int np = getNPoints();
//
// the points are sorted in order opposite to track direction -> outer points come 1st,
// but for the 2-leg cosmic track the innermost points are in the middle (1st lower leg, then upper one)
//
// start along track direction, i.e. last point in the ordered array
int minPar = mNLocPar;
for (int ip = getInnerPointID() + 1; ip--;) { // collision track or cosmic lower leg
AlignmentPoint* pnt = getPoint(ip);
pnt->setMinLocVarID(minPar);
if (pnt->containsMaterial()) {
mNLocPar += pnt->getNMatPar();
}
pnt->setMaxLocVarID(mNLocPar); // flag up to which parameted ID this points depends on
}
//
if (isCosmic()) {
minPar = mNLocPar;
for (int ip = getInnerPointID() + 1; ip < np; ip++) { // collision track or cosmic lower leg
AlignmentPoint* pnt = getPoint(ip);
pnt->setMinLocVarID(minPar);
if (pnt->containsMaterial()) {
mNLocPar += pnt->getNMatPar();
}
pnt->setMaxLocVarID(mNLocPar); // flag up to which parameted ID this points depends on
}
}
mLocPar.clear();
mLocPar.resize(mNLocPar);
for (int i = 0; i < 2; i++) {
mResid[i].clear();
mDResDLoc[i].clear();
mResid[i].resize(np);
mDResDLoc[i].resize(mNLocPar * np);
}
}
//______________________________________________________
bool AlignmentTrack::calcResidDeriv(double* params)
{
// Propagate for given local params and calculate residuals and their derivatives.
// The 1st 4 or 5 elements of params vector should be the reference trackParam_t
// Then parameters of material corrections for each point
// marked as having materials should come (4 or 5 dependending if ELoss is varied or fixed).
// They correspond to kink parameters
// (trackParam_t_after_material - trackParam_t_before_material)
// rotated to frame where they error matrix is diagonal. Their conversion to trackParam_t
// increment will be done locally in the applyMatCorr routine.
//
// If params are not provided, use internal params array
//
if (!params) {
params = mLocPar.data();
}
//
if (!getResidDone()) {
calcResiduals(params);
}
//
int np = getNPoints();
//
const auto& algConf = AlignConfig::Instance();
// collision track or cosmic lower leg
if (!calcResidDeriv(params, mNeedInv[0], getInnerPointID(), 0)) {
if (algConf.verbose > 2) {
LOG(warn) << "Failed on derivatives calculation 0";
}
return false;
}
//
if (isCosmic()) { // cosmic upper leg
if (!calcResidDeriv(params, mNeedInv[1], getInnerPointID() + 1, np - 1)) {
if (algConf.verbose > 2) {
LOG(warn) << "Failed on derivatives calculation 0";
}
}
}
//
setDerivDone();
return true;
}
//______________________________________________________
bool AlignmentTrack::calcResidDeriv(double* extendedParams, bool invert, int pFrom, int pTo)
{
// Calculate derivatives of residuals vs params for points pFrom to pT. For cosmic upper leg
// track parameter may require inversion.
// The 1st 4 or 5 elements of params vector should be the reference trackParam_t
// Then parameters of material corrections for each point
// marked as having materials should come (4 or 5 dependending if ELoss is varied or fixed).
// They correspond to kink parameters
// (trackParam_t_after_material - trackParam_t_before_material)
// rotated to frame where they error matrix is diagonal. Their conversion to trackParam_t
// increment will be done locally in the applyMatCorr routine.
//
// The derivatives are calculated using Richardson extrapolation
// (like http://root.cern.ch/root/html/ROOT__Math__RichardsonDerivator.html)
//
const auto& algConf = AlignConfig::Instance();
trackPar_t probD[kNRDClones]; // use this to vary supplied param for derivative calculation
double varDelta[kRichardsonN];
const int kInvElem[kNKinParBON] = {-1, 1, 1, -1, -1};
//
const double kDelta[kNKinParBON] = {0.02, 0.02, 0.001, 0.001, 0.01}; // variations for ExtTrackParam and material effects
//
double delta[kNKinParBON]; // variations of curvature term are relative
for (int i = kNKinParBOFF; i--;) {
delta[i] = kDelta[i];
}
if (getFieldON()) {
delta[kParQ2Pt] = kDelta[kParQ2Pt] * Abs(getQ2Pt());
}
//
int pinc, signELoss = 0; // RS Validate for cosmic. Propagation is done from inner point to outer one:
// energy loss is applied for collision tracks and cosmic lower leg, compensated for cosmic upper leg
if (pTo > pFrom) { // fit in points decreasing order: cosmics upper leg
pTo++;
pinc = 1;
signELoss = 1; // eloss is corrected
} else { // fit in points increasing order: collision track or cosmics lower leg
pTo--;
pinc = -1;
signELoss = -1; // eloss is applied
}
// 1) derivative wrt trackParam_t parameters
for (int ipar = mNLocExtPar; ipar--;) {
setParams(probD, kNRDClones, getX(), getAlpha(), extendedParams, true);
if (invert) {
for (int ic = kNRDClones; ic--;) {
probD[ic].invert();
}
}
double del = delta[ipar];
//
for (int icl = 0; icl < kRichardsonN; icl++) { // calculate kRichardsonN variations with del, del/2, del/4...
varDelta[icl] = del;
modParam(probD[(icl << 1) + 0], ipar, del);
modParam(probD[(icl << 1) + 1], ipar, -del);
del *= 0.5;
}
// propagate varied tracks to each point
for (int ip = pFrom; ip != pTo; ip += pinc) { // points are ordered against track direction
AlignmentPoint* pnt = getPoint(ip);
// we propagate w/o mat. corrections, they will be accounted in applyMatCorr
if (!propagateParamToPoint(probD, kNRDClones, pnt, algConf.maxStep, algConf.maxSnp, MatCorrType::USEMatCorrNONE, signELoss)) {
return false;
}
if (!applyMatCorr(probD, kNRDClones, extendedParams, pnt)) {
return false;
}
if (pnt->containsMeasurement()) {
int offsDer = ip * mNLocPar + ipar;
richardsonDeriv(probD, varDelta, pnt, mDResDLoc[0][offsDer], mDResDLoc[1][offsDer]); // calculate derivatives
if (invert && kInvElem[ipar] < 0) {
mDResDLoc[0][offsDer] = -mDResDLoc[0][offsDer];
mDResDLoc[1][offsDer] = -mDResDLoc[1][offsDer];
}
}
} // loop over points
} // loop over ExtTrackParam parameters
// 2) now vary material effect related parameters: MS and eventually ELoss
for (int ip = pFrom; ip != pTo; ip += pinc) { // points are ordered against track direction
AlignmentPoint* pnt = getPoint(ip);
// global derivatives at this point
if (pnt->containsMeasurement() && !calcResidDerivGlo(pnt)) {
if (algConf.verbose > 2) {
LOGF(warn, "Failed on global derivatives calculation at point %d", ip);
pnt->print(AlignmentPoint::kMeasurementBit);
}
return false;
}
//
if (!pnt->containsMaterial()) {
continue;
}
//
int nParFreeI = pnt->getNMatPar();
//
// array delta gives desired variation of parameters in trackParam_t definition,
// while the variation should be done for parameters in the frame where the vector
// of material corrections has diagonal cov. matrix -> rotate the delta to this frame
double deltaMatD[kNKinParBON];
// pnt->diagMatCorr(delta, deltaMatD);
for (int ipar = 0; ipar < nParFreeI; ipar++) {
double d = pnt->getMatCorrCov()[ipar];
deltaMatD[ipar] = d > 0. ? Sqrt(d) * 5 : delta[ipar];
}
//
// printf("Vary %d [%+.3e %+.3e %+.3e %+.3e] ",ip,deltaMatD[0],deltaMatD[1],deltaMatD[2],deltaMatD[3]); pnt->print();
int offsI = pnt->getMaxLocVarID() - nParFreeI; // the parameters for this point start with this offset
// they are irrelevant for the points upstream
for (int ipar = 0; ipar < nParFreeI; ipar++) { // loop over DOFs related to MS and ELoss are point ip
double del = deltaMatD[ipar];
//
// We will vary the tracks starting from the original parameters propagated to given point
// and stored there (before applying material corrections for this point)
//
setParams(probD, kNRDClones, pnt->getXTracking(), pnt->getAlphaSens(), pnt->getTrParamWSB(), false);
// no need for eventual track inversion here: if needed, this is already done in ParamWSB
//
int offsIP = offsI + ipar; // parameter entry in the extendedParams array
// printf(" Var:%d (%d) %e\n",ipar,offsIP, del);
for (int icl = 0; icl < kRichardsonN; icl++) { // calculate kRichardsonN variations with del, del/2, del/4...
varDelta[icl] = del;
double parOrig = extendedParams[offsIP];
extendedParams[offsIP] += del;
//
// apply varied material effects : incremented by delta
if (!applyMatCorr(probD[(icl << 1) + 0], extendedParams, pnt)) {
return false;
}
//
// apply varied material effects : decremented by delta
extendedParams[offsIP] = parOrig - del;
if (!applyMatCorr(probD[(icl << 1) + 1], extendedParams, pnt)) {
return false;
}
//
extendedParams[offsIP] = parOrig;
del *= 0.5;
}
if (pnt->containsMeasurement()) { // calculate derivatives at the scattering point itself
int offsDerIP = ip * mNLocPar + offsIP;
richardsonDeriv(probD, varDelta, pnt, mDResDLoc[0][offsDerIP], mDResDLoc[1][offsDerIP]); // calculate derivatives for ip
// printf("DR SELF: %e %e at %d (%d)\n",mDResDLoc[0][offsDerIP], mDResDLoc[1][offsDerIP],offsI, offsDerIP);
}
//
// loop over points whose residuals can be affected by the material effects on point ip
for (int jp = ip + pinc; jp != pTo; jp += pinc) {
AlignmentPoint* pntJ = getPoint(jp);
// printf(" DerFor:%d ",jp); pntJ->print();
if (!propagateParamToPoint(probD, kNRDClones, pntJ, algConf.maxStep, algConf.maxSnp, MatCorrType::USEMatCorrNONE, signELoss)) {
return false;
}
//
if (pntJ->containsMaterial()) { // apply material corrections
if (!applyMatCorr(probD, kNRDClones, extendedParams, pntJ)) {
return false;
}
}
//
if (pntJ->containsMeasurement()) {
int offsDerJ = jp * mNLocPar + offsIP;
// calculate derivatives
richardsonDeriv(probD, varDelta, pntJ, mDResDLoc[0][offsDerJ], mDResDLoc[1][offsDerJ]);
}
//
} // << loop over points whose residuals can be affected by the material effects on point ip
} // << loop over DOFs related to MS and ELoss are point ip
} // << loop over all points of the track
//
return true;
}
//______________________________________________________
bool AlignmentTrack::calcResidDerivGlo(AlignmentPoint* pnt)
{
// calculate residuals derivatives over point's sensor and its parents global params
double deriv[AlignableVolume::kNDOFGeom * 3];
//
const AlignableSensor* sens = pnt->getSensor();
const AlignableVolume* vol = sens;
// precalculated track parameters
double snp = pnt->getTrParamWSA(kParSnp), tgl = pnt->getTrParamWSA(kParTgl);
// precalculate track slopes to account tracking X variation
// these are coeffs to translate deltaX of the point to deltaY and deltaZ of track
double cspi = 1. / Sqrt((1 - snp) * (1 + snp)), slpY = snp * cspi, slpZ = tgl * cspi;
//
pnt->setDGloOffs(mNGloPar); // mark 1st entry of derivatives
do {
// measurement residuals
int nfree = vol->getNDOFsFree();
if (!nfree) {
continue;
} // no free parameters?
sens->dPosTraDParGeom(pnt, deriv, vol == sens ? nullptr : vol);
//
checkExpandDerGloBuffer(mNGloPar + nfree); // if needed, expand derivatives buffer
//
for (int ip = 0; ip < AlignableVolume::kNDOFGeom; ip++) { // we need only free parameters
if (!vol->isFreeDOF(ip)) {
continue;
}
double* dXYZ = &deriv[ip * 3]; // tracking XYZ derivatives over this parameter
// residual is defined as diagonalized track_estimate - measured Y,Z in tracking frame
// where the track is evaluated at measured X!
// -> take into account modified X using track parameterization at the point (paramWSA)
// Attention: small simplifications(to be checked if it is ok!!!):
// effect of changing X is accounted neglecting track curvature to preserve linearity
//
// store diagonalized residuals in track buffer
pnt->diagonalizeResiduals((dXYZ[AlignmentPoint::kX] * slpY - dXYZ[AlignmentPoint::kY]),
(dXYZ[AlignmentPoint::kX] * slpZ - dXYZ[AlignmentPoint::kZ]),
mDResDGlo[0][mNGloPar], mDResDGlo[1][mNGloPar]);
// and register global ID of varied parameter
mGloParID[mNGloPar] = vol->getParGloID(ip);
mNGloPar++;
}
//
} while ((vol = vol->getParent()));
//
// eventual detector calibration parameters
const AlignableDetector* det = sens->getDetector();
int ndof = 0;
if (det && (ndof = det->getNCalibDOFs())) {
// if needed, expand derivatives buffer
checkExpandDerGloBuffer(mNGloPar + det->getNCalibDOFsFree());
for (int idf = 0; idf < ndof; idf++) {
if (!det->isFreeDOF(idf)) {
continue;
}
sens->dPosTraDParCalib(pnt, deriv, idf, nullptr);
pnt->diagonalizeResiduals((deriv[AlignmentPoint::kX] * slpY - deriv[AlignmentPoint::kY]),
(deriv[AlignmentPoint::kX] * slpZ - deriv[AlignmentPoint::kZ]),
mDResDGlo[0][mNGloPar], mDResDGlo[1][mNGloPar]);
// and register global ID of varied parameter
mGloParID[mNGloPar] = det->getParGloID(idf);
mNGloPar++;
}
}
//
pnt->setNGloDOFs(mNGloPar - pnt->getDGloOffs()); // mark number of global derivatives filled
//
return true;
}
//______________________________________________________
bool AlignmentTrack::calcResiduals(const double* extendedParams)
{
// Propagate for given local params and calculate residuals
// The 1st 4 or 5 elements of extendedParams vector should be the reference trackParam_t
// Then parameters of material corrections for each point
// marked as having materials should come (4 or 5 dependending if ELoss is varied or fixed).
// They correspond to kink parameters
// (trackParam_t_after_material - trackParam_t_before_material)
// rotated to frame where they error matrix is diagonal. Their conversion to trackParam_t
// increment will be done locally in the applyMatCorr routine.
//
// If extendedParams are not provided, use internal extendedParams array
//
if (!extendedParams) {
extendedParams = mLocPar.data();
}
int np = getNPoints();
mChi2 = 0;
mNDF = 0;
//
const auto& algConf = AlignConfig::Instance();
// collision track or cosmic lower leg
if (!calcResiduals(extendedParams, mNeedInv[0], getInnerPointID(), 0)) {
if (algConf.verbose > 2) {
LOG(warn) << "Failed on residuals calculation 0";
}
return false;
}
//
if (isCosmic()) { // cosmic upper leg
if (!calcResiduals(extendedParams, mNeedInv[1], getInnerPointID() + 1, np - 1)) {
if (algConf.verbose > 2) {
LOG(warn) << "Failed on residuals calculation 1";
}
return false;
}
}
//
mNDF -= mNLocExtPar;
setResidDone();
return true;
}
//______________________________________________________
bool AlignmentTrack::calcResiduals(const double* extendedParams, bool invert, int pFrom, int pTo)
{
// Calculate residuals for the single leg from points pFrom to pT
// The 1st 4 or 5 elements of extendedParams vector should be corrections to
// the reference trackParam_t
// Then parameters of material corrections for each point
// marked as having materials should come (4 or 5 dependending if ELoss is varied or fixed).
// They correspond to kink parameters
// (trackParam_t_after_material - trackParam_t_before_material)
// rotated to frame where they error matrix is diagonal. Their conversion to trackParam_t
// increment will be done locally in the applyMatCorr routine.
//
trackParam_t probe;
setParams(probe, getX(), getAlpha(), extendedParams, true);
if (invert) {
probe.invert();
}
int pinc, signELoss = 0; // RS Validate for cosmic. Propagation is done from inner point to outer one:
// energy loss is applied for collision tracks and cosmic lower leg, compensated for cosmic upper leg
if (pTo > pFrom) { // fit in points decreasing order: cosmics upper leg
pTo++;
pinc = 1;
signELoss = 1; // eloss is corrected
} else { // fit in points increasing order: collision track or cosmics lower leg
pTo--;
pinc = -1;
signELoss = -1; // eloss is applied
}
//
const auto& algConf = AlignConfig::Instance();
for (int ip = pFrom; ip != pTo; ip += pinc) { // points are ordered against track direction:
AlignmentPoint* pnt = getPoint(ip);
if (!propagateParamToPoint(probe, pnt, algConf.maxStep, algConf.maxSnp, MatCorrType::USEMatCorrNONE, signELoss)) {
return false;
}
//
// store the current track kinematics at the point BEFORE applying eventual material
// corrections. This kinematics will be later varied around supplied parameters (in the calcResidDeriv)
pnt->setTrParamWSB(probe.getParams());
// account for materials
if (!applyMatCorr(probe, extendedParams, pnt)) {
return false;
}
pnt->setTrParamWSA(probe.getParams());
//
if (pnt->containsMeasurement()) { // need to calculate residuals in the frame where errors are orthogonal
pnt->getResidualsDiag(probe.getParams(), mResid[0][ip], mResid[1][ip]);
mChi2 += mResid[0][ip] * mResid[0][ip] / pnt->getErrDiag(0);
mChi2 += mResid[1][ip] * mResid[1][ip] / pnt->getErrDiag(1);
mNDF += 2;
}
//
if (pnt->containsMaterial()) {
// material degrees of freedom do not contribute to NDF since they are constrained by 0 expectation
int nCorrPar = pnt->getNMatPar();
const float* corCov = pnt->getMatCorrCov(); // correction diagonalized covariance
auto offs = pnt->getMaxLocVarID() - nCorrPar;
for (int i = 0; i < nCorrPar; i++) {
mChi2 += mLocPar[offs + i] * mLocPar[offs + i] / corCov[i];
}
}
}
return true;
}
//______________________________________________________
bool AlignmentTrack::propagateParamToPoint(trackPar_t* tr, int nTr, const AlignmentPoint* pnt, double maxStep, double maxSnp, MatCorrType mt, int signCorr)
{
// Propagate set of tracks to the point (only parameters, no error matrix)
// VECTORIZE this
//
const auto& algConf = AlignConfig::Instance();
for (int itr = nTr; itr--;) {
if (!propagateParamToPoint(tr[itr], pnt, maxStep, maxSnp, mt, signCorr)) {
if (algConf.verbose > 2) {
LOG(error) << "Failed on clone " << itr << " propagation ";
tr[itr].printParam();
pnt->print(AlignmentPoint::kMeasurementBit | AlignmentPoint::kMaterialBit);
}
return false;
}
}
return true;
}
//______________________________________________________
bool AlignmentTrack::propagateParamToPoint(trackPar_t& tr, const AlignmentPoint* pnt, double maxStep, double maxSnp, MatCorrType mt, int signCorr)
{
// propagate tracks to the point (only parameters, no error matrix)
return propagate(tr, pnt, maxStep, maxSnp, mt, nullptr, signCorr);
}
//______________________________________________________
bool AlignmentTrack::propagateToPoint(trackParam_t& tr, trackPar_t* linRef, const AlignmentPoint* pnt, double maxStep, double maxSnp, MatCorrType mt, track::TrackLTIntegral* tLT, int signCorr)
{
// propagate tracks to the point. If matCor is true, then material corrections will be applied.
// if matPar pointer is provided, it will be filled by total x2x0 and signed xrho
return propagate(tr, linRef, pnt, maxStep, maxSnp, mt, tLT, signCorr);
}
bool AlignmentTrack::propagate(trackParam_t& track, trackPar_t* linRef, const AlignmentPoint* pnt, double maxStep, double maxSnp, MatCorrType mt, track::TrackLTIntegral* tLT, int signCorr)
{
if (signCorr == 0) { // auto
// calculate the sign of the energy loss correction and ensure the upper leg of cosmics is calculated correctly.
double dx = pnt->getXTracking() - track.getX();
int dir = dx > 0.f ? 1 : -1;
signCorr = pnt->isInvDir() ? dir : -dir; // propagation along the track direction should have signCorr=-1
}
// do propagation in at least 2 step to reveal eventual effect of MS on the position
return PropagatorD::Instance()->propagateToAlphaX(track, linRef, pnt->getAlphaSens(), pnt->getXTracking(), pnt->getUseBzOnly(), maxSnp, maxStep, 2, mt, tLT, signCorr);
}
bool AlignmentTrack::propagate(trackPar_t& track, const AlignmentPoint* pnt, double maxStep, double maxSnp, MatCorrType mt, track::TrackLTIntegral* tLT, int signCorr)
{
if (signCorr == 0) { // auto
// calculate the sign of the energy loss correction and ensure the upper leg of cosmics is calculated correctly.
double dx = pnt->getXTracking() - track.getX();
int dir = dx > 0.f ? 1 : -1;
signCorr = pnt->isInvDir() ? dir : -dir; // propagation along the track direction should have signCorr=-1
}
// do propagation in at least 2 step to reveal eventual effect of MS on the position
return PropagatorD::Instance()->propagateToAlphaX(track, pnt->getAlphaSens(), pnt->getXTracking(), pnt->getUseBzOnly(), maxSnp, maxStep, 2, mt, tLT, signCorr);
}
/*
//______________________________________________________
bool AlignmentTrack::ApplyMS(trackParam_t& trPar, double tms,double pms)
{
//------------------------------------------------------------------------------
// Modify track par (e.g. trackParam_t) in the tracking frame
// (dip angle lam, az. angle phi)
// by multiple scattering defined by polar and azumuthal scattering angles in
// the track collinear frame (tms and pms resp).
// The updated direction vector in the tracking frame becomes
//
// | Cos[lam]*Cos[phi] Cos[phi]*Sin[lam] -Sin[phi] | | Cos[tms] |
// | Cos[lam]*Sin[phi] Sin[lam]*Sin[phi] Cos[phi] | x | Cos[pms]*Sin[tms]|
// | Sin[lam] -Cos[lam] 0 | | Sin[pms]*Sin[tms]|
//
//------------------------------------------------------------------------------
//
double *par = (double*) trPar.GetParameter();
//
if (Abs(tms)<1e-7) return true;
//
double snTms = Sin(tms), csTms = Cos(tms);
double snPms = Sin(pms), csPms = Cos(pms);
double snPhi = par[2], csPhi = Sqrt((1.-snPhi)*(1.+snPhi));
double csLam = 1./Sqrt(1.+par[3]*par[3]), snLam = csLam*par[3];
//
double r00 = csLam*csPhi, r01 = snLam*csPhi, &r02 = snPhi;
double r10 = csLam*snPhi, r11 = snLam*snPhi, &r12 = csPhi;
double &r20 = snLam ,&r21 = csLam;
//
double &v0 = csTms, v1 = snTms*csPms, v2 = snTms*snPms;
//
double px = r00*v0 + r01*v1 - r02*v2;
double py = r10*v0 + r11*v1 + r12*v2;
double pz = r20*v0 - r21*v1;
//
double pt = Sqrt(px*px + py*py);
par[2] = py/pt;
par[3] = pz/pt;
par[4]*= csLam/pt;
//
return true;
}
*/
//______________________________________________________
bool AlignmentTrack::applyMatCorr(trackPar_t& trPar, const double* corrPar, const AlignmentPoint* pnt)
{
// Modify track param (e.g. trackParam_t) in the tracking frame
// by delta accounting for material effects
// Note: corrPar contains delta to track parameters rotated by the matrix
// DIAGONALIZING ITS COVARIANCE MATRIX!
// transform parameters from the frame diagonalizing the errors to track frame
double corr[kNKinParBON] = {0};
if (pnt->containsMaterial()) { // are there free params from materials?
int nCorrPar = pnt->getNMatPar();
const double* corrDiag = &corrPar[pnt->getMaxLocVarID() - nCorrPar]; // material corrections for this point start here
pnt->unDiagMatCorr(corrDiag, corr); // this is to account for MS and RANDOM Eloss (if varied)
}
// to this we should add expected parameters modification due to the deterministic eloss
float* detELoss = pnt->getMatCorrExp();
for (int i = kNKinParBON; i--;) {
corr[i] += detELoss[i];
}
//corr[kParQ2Pt] += detELoss[kParQ2Pt];
// printf("apply corr UD %+.3e %+.3e %+.3e %+.3e %+.3e\n",corr[0],corr[1],corr[2],corr[3],corr[4]);
// printf(" corr D %+.3e %+.3e %+.3e %+.3e\n",corrDiag[0],corrDiag[1],corrDiag[2],corrDiag[3]);
// printf("at point :"); pnt->print();
return applyMatCorr(trPar, corr);
//
}
//______________________________________________________
bool AlignmentTrack::applyMatCorr(trackPar_t& trPar, const double* corr)
{
// Modify track param (e.g. trackParam_t) in the tracking frame
// by delta accounting for material effects
// Note: corr contains delta to track frame, NOT in diagonalized one
const double snp = trPar.getSnp() + corr[kParSnp];
const auto& algConf = AlignConfig::Instance();
if (Abs(snp) > algConf.maxSnp) {
if (algConf.verbose > 2) {
LOG(error) << "Snp is too large: " << snp;
printf("DeltaPar: ");
for (int i = 0; i < kNKinParBON; i++) {
printf("%+.3e ", corr[i]);
}
printf("\n");
trPar.printParam();
}
return false;
}
trPar.updateParams(corr);
return true;
}
//______________________________________________________
bool AlignmentTrack::applyMatCorr(trackPar_t* trSet, int ntr, const double* corrDiag, const AlignmentPoint* pnt)
{
// Modify set of track params (e.g. trackParam_t) in the tracking frame
// by delta accounting for material effects
// Note: corrDiag contain delta to track parameters rotated by the matrix DIAGONALIZING ITS
// COVARIANCE MATRIX
// transform parameters from the frame diagonalizing the errors to track frame
const auto& algConf = AlignConfig::Instance();
double corr[kNKinParBON] = {0};
if (pnt->containsMaterial()) { // are there free params from materials?
int nCorrPar = pnt->getNMatPar();
const double* corrDiagP = &corrDiag[pnt->getMaxLocVarID() - nCorrPar]; // material corrections for this point start here
pnt->unDiagMatCorr(corrDiagP, corr);
}
float* detELoss = pnt->getMatCorrExp();
for (int i = kNKinParBON; i--;) {
corr[i] += detELoss[i];
}
// if (!pnt->getELossVaried()) corr[kParQ2Pt] = pnt->getMatCorrExp()[kParQ2Pt]; // fixed eloss expected effect
// printf("apply corr UD %+.3e %+.3e %+.3e %+.3e\n",corr[0],corr[1],corr[2],corr[3]);
// printf(" corr D %+.3e %+.3e %+.3e %+.3e\n",corrDiagP[0],corrDiagP[1],corrDiagP[2],corrDiagP[3]);
// printf("at point :"); pnt->print();
//
for (int itr = ntr; itr--;) {
if (!applyMatCorr(trSet[itr], corr)) {
if (algConf.verbose > 2) {
LOGP(error, "Failed on clone {} materials", itr);
trSet[itr].printParam();
}
return false;
}
}
return true;
}
//______________________________________________
double AlignmentTrack::richardsonExtrap(double* val, int ord)
{
// Calculate Richardson extrapolation of order ord (starting from 1)
// The array val should contain estimates ord+1 of derivatives with variations
// d, d/2 ... d/2^ord.
// The array val is overwritten
//
if (ord == 1) {
return (4. * val[1] - val[0]) * (1. / 3);
}
do {
for (int i = 0; i < ord; i++) {
val[i] = (4. * val[i + 1] - val[i]) * (1. / 3);
}
} while (--ord);
return val[0];
}
//______________________________________________
double AlignmentTrack::richardsonExtrap(const double* val, int ord)
{
// Calculate Richardson extrapolation of order ord (starting from 1)
// The array val should contain estimates ord+1 of derivatives with variations
// d, d/2 ... d/2^ord.
// The array val is not overwritten
//
if (ord == 1) {
return (4. * val[1] - val[0]) * (1. / 3);
}
double* buff = new double[ord + 1];
memcpy(buff, val, (ord + 1) * sizeof(double));
do {
for (int i = 0; i < ord; i++) {
buff[i] = (4. * buff[i + 1] - buff[i]) * (1. / 3);
}
} while (--ord);
return buff[0];
}
//______________________________________________
void AlignmentTrack::richardsonDeriv(const trackPar_t* trSet, const double* delta, const AlignmentPoint* pnt, double& derY, double& derZ)
{
// Calculate Richardson derivatives for diagonalized Y and Z from a set of kRichardsonN pairs
// of tracks with same parameter of i-th pair varied by +-delta[i]
static double derRichY[kRichardsonN], derRichZ[kRichardsonN];
//
for (int icl = 0; icl < kRichardsonN; icl++) { // calculate kRichardsonN variations with del, del/2, del/4...
double resYVP = 0, resYVN = 0, resZVP = 0, resZVN = 0;
pnt->getResidualsDiag(trSet[(icl << 1) + 0].getParams(), resYVP, resZVP); // variation with +delta
pnt->getResidualsDiag(trSet[(icl << 1) + 1].getParams(), resYVN, resZVN); // variation with -delta
derRichY[icl] = 0.5 * (resYVP - resYVN) / delta[icl]; // 2-point symmetric derivatives
derRichZ[icl] = 0.5 * (resZVP - resZVN) / delta[icl];
}
derY = richardsonExtrap(derRichY, kRichardsonOrd); // dY/dPar
derZ = richardsonExtrap(derRichZ, kRichardsonOrd); // dZ/dPar
if (TMath::IsNaN(derY) || TMath::IsNaN(derZ)) {
LOGP(error, "NAN encounterd: DerY {} : DerZ {}", derY, derZ);
}
//
}
//______________________________________________
void AlignmentTrack::Print(Option_t* opt) const
{
// print track data
printf("%s ", isCosmic() ? " Cosmic " : "Collision ");
trackParam_t::print();
printf("N Free Par: %d (Kinem: %d) | Npoints: %d (Inner:%d) | Chi2Ini:%.1f Chi2: %.1f/%d",
mNLocPar, mNLocExtPar, getNPoints(), getInnerPointID(), mChi2Ini, mChi2, mNDF);
if (isCosmic()) {
int npLow = getInnerPointID();
int npUp = getNPoints() - npLow - 1;
printf(" [Low:%.1f/%d Up:%.1f/%d]", mChi2CosmDn, npLow, mChi2CosmUp, npUp);
}
printf("\n");
//
TString optS = opt;
optS.ToLower();
bool res = optS.Contains("r") && getResidDone();
bool der = optS.Contains("d") && getDerivDone();
bool par = optS.Contains("lc"); // local param corrections
bool paru = optS.Contains("lcu"); // local param corrections in track param frame
//
if (par) {
printf("Ref.track corr: ");
for (int i = 0; i < mNLocExtPar; i++) {
printf("%+.3e ", mLocPar[i]);
}
printf("\n");
}
//
if (optS.Contains("p") || res || der) {
for (int ip = 0; ip < getNPoints(); ip++) {
printf("#%3d ", ip);
auto* pnt = getPoint(ip);
pnt->print(AlignmentPoint::kMeasurementBit); // RS FIXME OPT
//
if (res && pnt->containsMeasurement()) {
printf(" Residuals : %+.3e %+.3e -> Pulls: %+7.2f %+7.2f\n",
getResidual(0, ip), getResidual(1, ip),
getResidual(0, ip) / sqrt(pnt->getErrDiag(0)), getResidual(1, ip) / sqrt(pnt->getErrDiag(1)));
}
if (der && pnt->containsMeasurement()) {
for (int ipar = 0; ipar < mNLocPar; ipar++) {
printf(" Dres/dp%03d : %+.3e %+.3e\n", ipar, getDResDLoc(0, ip)[ipar], getDResDLoc(1, ip)[ipar]);
}
}
//
if (par && pnt->containsMaterial()) { // material corrections
int nCorrPar = pnt->getNMatPar();
printf(" Corr.Diag: ");
for (int i = 0; i < nCorrPar; i++) {
printf("%+.3e ", mLocPar[i + pnt->getMaxLocVarID() - nCorrPar]);
}
printf("\n");
printf(" Corr.Pull: ");
const float* corCov = pnt->getMatCorrCov(); // correction covariance
// const float *corExp = pnt->getMatCorrExp(); // correction expectation
for (int i = 0; i < nCorrPar; i++) {
printf("%+.3e ", (mLocPar[i + pnt->getMaxLocVarID() - nCorrPar] /* - corExp[i]*/) / Sqrt(corCov[i]));
}
printf("\n");
if (paru) { // print also mat.corrections in track frame
double corr[5] = {0};
pnt->unDiagMatCorr(&mLocPar[pnt->getMaxLocVarID() - nCorrPar], corr);
// if (!pnt->getELossVaried()) corr[kParQ2Pt] = pnt->getMatCorrExp()[kParQ2Pt]; // fixed eloss expected effect
printf(" Corr.Track: ");
for (int i = 0; i < kNKinParBON; i++) {
printf("%+.3e ", corr[i]);
}
printf("\n");
}
}
}
} // print points
}
//______________________________________________
void AlignmentTrack::dumpCoordinates() const
{
// print various coordinates for inspection
printf("gpx/D:gpy/D:gpz/D:gtxb/D:gtyb/D:gtzb/D:gtxa/D:gtya/D:gtza/D:alp/D:px/D:py/D:pz/D:tyb/D:tzb/D:tya/D:tza/D:ey/D:ez/D\n");
for (int ip = 0; ip < getNPoints(); ip++) {
auto* pnt = getPoint(ip);
if (!pnt->containsMeasurement()) {
continue;
}
pnt->dumpCoordinates();
}
}
//______________________________________________
bool AlignmentTrack::iniFit()
{
// perform initial fit of the track
//
const auto& algConf = AlignConfig::Instance();
if (!getFieldON()) { // for field-off data impose nominal momentum
setQ2Pt(isCosmic() ? 1. / algConf.defPTB0Cosm : 1. / algConf.defPTB0Coll);
}
trackParam_t trc(*(trackParam_t*)this);
mChi2 = mChi2CosmUp = mChi2CosmDn = 0;
//
// the points are ranged from outer to inner for collision tracks,
// and from outer point of lower leg to outer point of upper leg for the cosmic track
//
// the fit will always start from the outgoing track in inward direction
if (!fitLeg(trc, 0, getInnerPointID(), mNeedInv[0])) {
if (algConf.verbose > 2) {
LOG(warn) << "Failed fitLeg 0";
trc.print();
}
return false; // collision track or cosmic lower leg
}
//
// printf("Lower leg: %d %d\n",0,getInnerPointID()); trc.print();
//
if (isCosmic()) {
mChi2CosmDn = mChi2;
trackParam_t trcU = trc;
if (!fitLeg(trcU, getNPoints() - 1, getInnerPointID() + 1, mNeedInv[1])) { //fit upper leg of cosmic track
if (algConf.verbose > 2) {
LOG(warn) << "Failed fitLeg 1";
trc.print();
}
return false; // collision track or cosmic lower leg
}
//
// propagate to reference point, which is the inner point of lower leg
const AlignmentPoint* refP = getPoint(getInnerPointID());
if (!propagateToPoint(trcU, nullptr, refP, algConf.maxStep, algConf.maxSnp, MatCorrType(algConf.matCorType), nullptr, -1)) { // moving along the track: energy is lost
return false;
}
//
mChi2CosmUp = mChi2 - mChi2CosmDn;
// printf("Upper leg: %d %d\n",getInnerPointID()+1,getNPoints()-1); trcU.print();
//
if (!combineTracks(trc, trcU)) {
return false;
}
//printf("Combined\n"); trc.print();
}
copyFrom(&trc);
//
mChi2Ini = mChi2;
return true;
}
//______________________________________________
bool AlignmentTrack::combineTracks(trackParam_t& trcL, const trackParam_t& trcU)
{
// Assign to trcL the combined tracks (Kalman update of trcL by trcU)
// The trcL and trcU MUST be defined at same X,Alpha
//
// Update equations: tracks described by vectors vL and vU and coviriances CL and CU resp.
// then the gain matrix K = CL*(CL+CU)^-1
// Updated vector and its covariance:
// CL' = CL - K*CL
// vL' = vL + K(vU-vL)
//
const auto& algConf = AlignConfig::Instance();
if (Abs(trcL.getX() - trcU.getX()) > TinyDist || Abs(trcL.getAlpha() - trcU.getAlpha()) > TinyDist) {
if (algConf.verbose > 2) {
LOG(error) << "Tracks must be defined at same reference X and Alpha";
trcL.print();
trcU.print();
}
return false;
}
//
LOGP(debug, "CosmDn: {}", trcL.asString());
LOGP(debug, "CosmUp: {}", trcU.asString());
float dsnp = trcL.getSnp() - trcU.getSnp(), dTgl = trcL.getTgl() - trcU.getTgl();
if (std::abs(dsnp) > algConf.cosmMaxDSnp || std::abs(dTgl) > algConf.cosmMaxDTgl) {
if (algConf.verbose > 2) {
LOGP(error, "Rejecting track with dSnp={} dTgl={}", dsnp, dTgl);
LOGP(error, "CosmDn: {}", trcL.asString());
LOGP(error, "CosmUp: {}", trcU.asString());
}
return false;
}
// const covMat_t& covU = trcU.getCov();
// const covMat_t& covL = trcL.getCov();
//
int mtSize = getFieldON() ? kNKinParBON : kNKinParBOFF;
TMatrixD matCL(mtSize, mtSize), matCLplCU(mtSize, mtSize);
TVectorD vl(mtSize), vUmnvL(mtSize);
//
// trcL.print();
// trcU.print();
//
for (int i = mtSize; i--;) {
vUmnvL[i] = trcU.getParam(i) - trcL.getParam(i); // y = residual of 2 tracks
vl[i] = trcL.getParam(i);
for (int j = i + 1; j--;) {
int indIJ = ((i * (i + 1)) >> 1) + j; // position of IJ cov element in the trackParam_t covariance array
matCL(i, j) = matCL(j, i) = trcL.getCovarElem(i, j);
matCLplCU(i, j) = matCLplCU(j, i) = trcL.getCovarElem(i, j) + trcU.getCovarElem(i, j);
}
}
matCLplCU.Invert(); // S^-1 = (Cl + Cu)^-1
if (!matCLplCU.IsValid()) {
if (algConf.verbose > 2) {
LOG(error) << "Failed to invert summed cov.matrix of cosmic track";
matCLplCU.Print();
}
return false; // inversion failed
}
TMatrixD matK(matCL, TMatrixD::kMult, matCLplCU); // gain K = Cl*(Cl+Cu)^-1
TMatrixD matKdotCL(matK, TMatrixD::kMult, matCL); // K*Cl
TVectorD vlUp = matK * vUmnvL; // K*(vl - vu)
for (int i = mtSize; i--;) {
trcL.updateParam(vlUp[i], i); // updated param: vL' = vL + K(vU-vL)
for (int j = i + 1; j--;) {
trcL.updateCov(-matKdotCL(i, j), i, j);
} // updated covariance: Cl' = Cl - K*Cl
}
//
// update chi2
double chi2 = 0;
for (int i = mtSize; i--;) {
for (int j = mtSize; j--;) {
chi2 += matCLplCU(i, j) * vUmnvL[i] * vUmnvL[j];
}
}
mChi2 += chi2;
//
LOGP(debug, "CosmCB: {}", trcL.asString());
LOGP(debug, "Combined: Chi2Tot:{} ChiUp:{} ChiDn:{} ChiCmb:{} DSnp:{} DTgl:{} Alp:{}", mChi2, mChi2CosmUp, mChi2CosmDn, chi2, dsnp, dTgl, trcL.getAlpha());
return true;
}
//______________________________________________