forked from AliceO2Group/AliceO2
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathTrackResiduals.cxx
More file actions
1570 lines (1472 loc) · 53.9 KB
/
TrackResiduals.cxx
File metadata and controls
1570 lines (1472 loc) · 53.9 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 TrackResiduals.cxx
/// \brief Implementation of the TrackResiduals class
///
/// \author Ole Schmidt, ole.schmidt@cern.ch
///
///
#include "SpacePoints/TrackResiduals.h"
#include "CommonConstants/MathConstants.h"
#include "ReconstructionDataFormats/Track.h"
#include "MathUtils/fit.h"
#include "TMatrixDSym.h"
#include "TDecompChol.h"
#include "TVectorD.h"
#include <cmath>
#include <cstring>
#include <algorithm>
// for debugging
#include "TStopwatch.h"
#include "TSystem.h"
#include <iostream>
#include <fstream>
#include <limits>
#include <iomanip>
#include <fairlogger/Logger.h>
using namespace o2::tpc;
///////////////////////////////////////////////////////////////////////////////
///
/// initialization + binning
///
///////////////////////////////////////////////////////////////////////////////
//______________________________________________________________________________
void TrackResiduals::init(bool doBinning)
{
mSmoothPol2[VoxX] = true;
mSmoothPol2[VoxF] = true;
setKernelType();
mParams = &SpacePointsCalibConfParam::Instance();
mMaxZ2X = mParams->maxZ2X;
mIsInitialized = true;
if (doBinning) {
// initialize binning
initBinning();
}
LOG(info) << "Initialization complete";
}
//______________________________________________________________________________
void TrackResiduals::setY2XBinning(const std::vector<float>& binning)
{
if (mIsInitialized) {
LOG(error) << "Binning already initialized, not changing y/x binning";
return;
}
if (binning.size() == 0) {
LOGP(info, "Empty binning provided, will use default uniform y/x binning with {} bins", mNY2XBins);
return;
} else if (binning.size() == 1) {
const int bins = static_cast<int>(binning.at(0));
setNY2XBins(bins);
LOGP(info, "Setting uniform binning for y/x with {} bins", bins - 1);
return;
}
const int nBins = binning.size() - 1;
if (fabsf(binning[0] + 1.f) > param::sEps || fabsf(binning[nBins] - 1.f) > param::sEps) {
LOG(error) << "Provided binning for y/x not in range -1 to 1: " << binning[0] << " - " << binning[nBins] << ". Not changing y/x binning";
return;
}
LOGP(info, "Setting custom binning for y/x with {} bins", nBins);
setNY2XBins(nBins);
mUniformBins[VoxF] = false;
mY2XBinsDH.clear();
mY2XBinsDI.clear();
mY2XBinsCenter.clear();
for (int iBin = 0; iBin < nBins; ++iBin) {
mY2XBinsDH.push_back(.5f * (binning[iBin + 1] - binning[iBin]));
mY2XBinsDI.push_back(.5f / mY2XBinsDH[iBin]);
mY2XBinsCenter.push_back(binning[iBin] + mY2XBinsDH[iBin]);
LOGF(info, "Bin %i: center (%.3f), half bin width (%.3f)", iBin, mY2XBinsCenter.back(), mY2XBinsDH.back());
}
}
//______________________________________________________________________________
void TrackResiduals::setZ2XBinning(const std::vector<float>& binning)
{
if (mIsInitialized) {
LOG(error) << "Binning already initialized, not changing z/x binning";
return;
}
if (binning.size() == 0) {
LOGP(info, "Empty binning provided, will use default uniform z/x binning with {} bins", mNZ2XBins);
return;
} else if (binning.size() == 1) {
const int bins = static_cast<int>(binning.at(0));
setNZ2XBins(bins);
LOGP(info, "Setting uniform binning for z/x with {} bins", bins);
return;
}
int nBins = binning.size() - 1;
if (fabsf(binning[0]) > param::sEps || fabsf(binning[nBins] - 1.f) > param::sEps) {
LOG(error) << "Provided binning for z/x not in range 0 to 1: " << binning[0] << " - " << binning[nBins] << ". Not changing z/x binning";
return;
}
LOGP(info, "Setting custom binning for z/x with {} bins", nBins);
setNZ2XBins(nBins);
mUniformBins[VoxZ] = false;
mZ2XBinsDH.clear();
mZ2XBinsDI.clear();
mZ2XBinsCenter.clear();
for (int iBin = 0; iBin < nBins; ++iBin) {
mZ2XBinsDH.push_back(.5f * (binning[iBin + 1] - binning[iBin]) * mMaxZ2X);
mZ2XBinsDI.push_back(.5f / mZ2XBinsDH[iBin]);
mZ2XBinsCenter.push_back(binning[iBin] * mMaxZ2X + mZ2XBinsDH[iBin]);
LOGF(info, "Bin %i: center (%.3f), half bin width (%.3f)", iBin, mZ2XBinsCenter.back(), mZ2XBinsDH.back());
}
}
//______________________________________________________________________________
void TrackResiduals::initBinning()
{
// initialize binning structures
//
// X binning
if (mNXBins > 0 && mNXBins < param::NPadRows) {
// uniform binning in X
LOGF(info, "X-binning is uniform with %i bins from %.2f to %.2f", mNXBins, param::MinX, param::MaxX);
mDXI = mNXBins / (param::MaxX - param::MinX);
mDX = 1.0f / mDXI;
mUniformBins[VoxX] = true;
} else {
// binning per pad row
LOGF(info, "X-binning is per pad-row");
mNXBins = param::NPadRows;
mUniformBins[VoxX] = false;
mDX = param::RowDX[0];
mDXI = 1.f / mDX; // should not be used
}
//
// Y/X binning
mMaxY2X.resize(mNXBins);
mDY2XI.resize(mNXBins);
mDY2X.resize(mNXBins);
//
for (int ix = 0; ix < mNXBins; ++ix) {
float x = getX(ix);
mMaxY2X[ix] = tan(.5f * SECPHIWIDTH) - sDeadZone / x;
mDY2XI[ix] = mNY2XBins / (2.f * mMaxY2X[ix]);
mDY2X[ix] = 1.f / mDY2XI[ix];
}
if (mUniformBins[VoxF]) {
LOGF(info, "Y/X-binning is uniform with %i bins from -MaxY2X to +MaxY2X (values depend on X-bin)", mNY2XBins);
for (int ip = 0; ip < mNY2XBins; ++ip) {
mY2XBinsDH.push_back(1.f / mNY2XBins);
mY2XBinsDI.push_back(.5f / mY2XBinsDH[ip]);
mY2XBinsCenter.push_back(-1.f + (ip + 0.5f) * 2.f * mY2XBinsDH[ip]);
LOGF(info, "Bin %i: center (%.3f), half bin width (%.3f)", ip, mY2XBinsCenter.back(), mY2XBinsDH.back());
}
}
//
// Z/X binning
mDZ2XI = mNZ2XBins / mMaxZ2X;
mDZ2X = 1.0f / mDZ2XI; // for uniform case only
if (mUniformBins[VoxZ]) {
LOGF(info, "Z/X-binning is uniform with %i bins from 0 to %f", mNZ2XBins, mMaxZ2X);
for (int iz = 0; iz < mNZ2XBins; ++iz) {
mZ2XBinsDH.push_back(.5f * mDZ2X);
mZ2XBinsDI.push_back(mDZ2XI);
mZ2XBinsCenter.push_back((iz + 0.5f) * mDZ2X);
LOGF(info, "Bin %i: center (%.3f), half bin width (%.3f)", iz, mZ2XBinsCenter.back(), mZ2XBinsDH.back());
}
}
//
mNVoxPerSector = mNY2XBins * mNZ2XBins * mNXBins;
LOGF(info, "Each TPC sector is divided into %i voxels", mNVoxPerSector);
}
//______________________________________________________________________________
void TrackResiduals::initResultsContainer(int iSec)
{
if (mInitResultsContainer.test(iSec)) {
return;
}
mInitResultsContainer.set(iSec);
mVoxelResults[iSec].resize(mNVoxPerSector);
for (int ix = 0; ix < mNXBins; ++ix) {
for (int ip = 0; ip < mNY2XBins; ++ip) {
for (int iz = 0; iz < mNZ2XBins; ++iz) {
const size_t binGlb = getGlbVoxBin(ix, ip, iz);
VoxRes& resVox = mVoxelResults[iSec][binGlb];
resVox.bvox[VoxX] = ix;
resVox.bvox[VoxF] = ip;
resVox.bvox[VoxZ] = iz;
resVox.bsec = iSec;
}
}
}
LOG(debug) << "initialized the container for the main results";
}
//______________________________________________________________________________
void TrackResiduals::reset()
{
for (int iSec = 0; iSec < SECTORSPERSIDE * SIDES; ++iSec) {
mXBinsIgnore[iSec].reset();
std::fill(mVoxelResults[iSec].begin(), mVoxelResults[iSec].end(), VoxRes());
std::fill(mValidFracXBins[iSec].begin(), mValidFracXBins[iSec].end(), 0);
}
}
//______________________________________________________________________________
int TrackResiduals::getRowID(float x) const
{
int ix;
if (x < param::RowX[param::NRowsAccumulated[0] - 1] + param::RowDX[0]) {
// we are in the IROC
ix = (x - (param::RowX[0] - .5f * param::RowDX[0])) / param::RowDX[0];
if (ix < 0) {
// x is smaller than the inner radius of the first pad row
ix = -1;
}
} else if (x >= param::RowX[param::NRowsAccumulated[param::NROCTypes - 2]] - .5f * param::RowDX[param::NROCTypes - 1]) {
// we are in the OROC3
ix = (x - (param::RowX[param::NRowsAccumulated[param::NROCTypes - 2]] - .5f * param::RowDX[param::NROCTypes - 1])) / param::RowDX[param::NROCTypes - 1] + param::NRowsAccumulated[param::NROCTypes - 2];
if (ix >= param::NPadRows) {
// x is larger than the outer radius of the last OROC pad row
ix = -1;
}
} else if (x > param::RowX[param::NRowsAccumulated[0]] - .5f * param::RowDX[1] && x < param::RowX[param::NRowsAccumulated[1] - 1] + .5f * param::RowDX[1]) {
// we are in the OROC1
ix = (x - (param::RowX[param::NRowsAccumulated[0]] - .5f * param::RowDX[1])) / param::RowDX[1] + param::NRowsAccumulated[0];
} else if (x > param::RowX[param::NRowsAccumulated[1]] - .5f * param::RowDX[2] && x < param::RowX[param::NRowsAccumulated[2] - 1] + .5f * param::RowDX[2]) {
// we are in the OROC2
ix = (x - (param::RowX[param::NRowsAccumulated[1]] - .5f * param::RowDX[2])) / param::RowDX[2] + param::NRowsAccumulated[1];
} else {
// x is in one of the gaps between the ROCs
ix = -1;
}
return ix;
}
bool TrackResiduals::findVoxelBin(int secID, float x, float y, float z, std::array<unsigned char, VoxDim>& bvox) const
{
// Z/X bin
if (fabs(z / x) > mMaxZ2X) {
return false;
}
int bz = getZ2XBinExact(secID < SECTORSPERSIDE ? z / x : -z / x);
if (bz < 0) {
return false;
}
// X bin
int bx = getXBinExact(x);
if (bx < 0 || bx >= mNXBins) {
return false;
}
// Y/X bin
int bp = getY2XBinExact(y / x, bx);
if (bp < 0 || bp >= mNY2XBins) {
return false;
}
bvox[VoxZ] = bz;
bvox[VoxX] = bx;
bvox[VoxF] = bp;
return true;
}
void TrackResiduals::setKernelType(KernelType kernel, float bwX, float bwP, float bwZ, float scX, float scP, float scZ)
{
// set kernel type and widths in terms of binning in x, y/x, z/x and define aux variables
mKernelType = kernel;
mKernelScaleEdge[VoxX] = scX;
mKernelScaleEdge[VoxF] = scP;
mKernelScaleEdge[VoxZ] = scZ;
mKernelWInv[VoxX] = (bwX > 0) ? 1. / bwX : 1.;
mKernelWInv[VoxF] = (bwP > 0) ? 1. / bwP : 1.;
mKernelWInv[VoxZ] = (bwZ > 0) ? 1. / bwZ : 1.;
if (mKernelType == KernelType::Epanechnikov) {
// bandwidth 1
mStepKern[VoxX] = static_cast<int>(nearbyint(bwX + 0.5));
mStepKern[VoxF] = static_cast<int>(nearbyint(bwP + 0.5));
mStepKern[VoxZ] = static_cast<int>(nearbyint(bwZ + 0.5));
} else if (mKernelType == KernelType::Gaussian) {
// look in ~5 sigma
mStepKern[VoxX] = static_cast<int>(nearbyint(bwX * 5. + 0.5));
mStepKern[VoxF] = static_cast<int>(nearbyint(bwP * 5. + 0.5));
mStepKern[VoxZ] = static_cast<int>(nearbyint(bwZ * 5. + 0.5));
} else {
LOG(error) << "given kernel type is not defined";
}
for (int i = VoxDim; i--;) {
if (mStepKern[i] < 1) {
mStepKern[i] = 1;
}
}
}
///////////////////////////////////////////////////////////////////////////////
///
/// processing functions
///
///////////////////////////////////////////////////////////////////////////////
void TrackResiduals::setStats(const std::vector<TrackResiduals::VoxStats>& statsIn, int iSec)
{
initResultsContainer(iSec);
std::vector<VoxRes>& secDataTmp = mVoxelResults[iSec];
for (int iVox = 0; iVox < mNVoxPerSector; ++iVox) {
secDataTmp[iVox].stat[VoxX] = statsIn[iVox].meanPos[VoxX];
secDataTmp[iVox].stat[VoxF] = statsIn[iVox].meanPos[VoxF];
secDataTmp[iVox].stat[VoxZ] = statsIn[iVox].meanPos[VoxZ];
secDataTmp[iVox].stat[VoxDim] = statsIn[iVox].nEntries;
}
}
void TrackResiduals::fillStats(int iSec)
{
initResultsContainer(iSec);
std::vector<VoxRes>& secDataTmp = mVoxelResults[iSec];
for (int iVox = 0; iVox < mNVoxPerSector; ++iVox) {
const auto& voxStat = mVoxStatsIn[iVox];
VoxRes& resVox = secDataTmp[iVox];
for (int iDim = VoxDim; iDim--;) {
const auto sumStat = (resVox.stat[VoxDim] + voxStat.nEntries);
if (sumStat == 0) {
continue;
}
double norm = 1. / sumStat;
resVox.stat[iDim] = (resVox.stat[iDim] * resVox.stat[VoxDim] + voxStat.meanPos[iDim] * voxStat.nEntries) * norm;
}
resVox.stat[VoxDim] += voxStat.nEntries;
}
}
//______________________________________________________________________________
void TrackResiduals::processSectorResiduals(int iSec)
{
LOGP(info, "Processing {} voxel residuals for sector {}", mLocalResidualsIn.size(), iSec);
initResultsContainer(iSec);
// effective t0 correction changes sign between A-/C-side
float effT0corr = (iSec < SECTORSPERSIDE) ? mEffT0Corr : -1. * mEffT0Corr;
std::vector<size_t> binData;
for (const auto& res : mLocalResidualsIn) {
binData.push_back(getGlbVoxBin(res.bvox));
}
// sort in voxel increasing order
std::vector<size_t> binIndices(binData.size());
o2::math_utils::SortData(binData, binIndices);
// fill the voxel statistics into the results container
std::vector<VoxRes>& secData = mVoxelResults[iSec];
// vectors holding the data for one voxel at a time
std::vector<float> dyVec;
std::vector<float> dzVec;
std::vector<float> tgVec;
// assuming we will always have around 1000 entries per voxel
dyVec.reserve(1e3);
dzVec.reserve(1e3);
tgVec.reserve(1e3);
size_t currVoxBin = -1;
unsigned int nPointsInVox = 0;
unsigned int nProcessed = 0;
while (nProcessed < binData.size()) {
// read all points, voxel by voxel
int idx = binIndices[nProcessed];
if (currVoxBin != binData[idx]) {
if (nPointsInVox) {
VoxRes& resVox = secData[currVoxBin];
processVoxelResiduals(dyVec, dzVec, tgVec, resVox);
}
currVoxBin = binData[idx];
nPointsInVox = 0;
dyVec.clear();
dzVec.clear();
tgVec.clear();
}
dyVec.push_back(mLocalResidualsIn[idx].dy * param::MaxResid / 0x7fff);
dzVec.push_back(mLocalResidualsIn[idx].dz * param::MaxResid / 0x7fff -
mEffVdriftCorr * secData[currVoxBin].stat[VoxZ] * secData[currVoxBin].stat[VoxX] -
effT0corr);
tgVec.push_back(mLocalResidualsIn[idx].tgSlp * param::MaxTgSlp / 0x7fff);
++nPointsInVox;
++nProcessed;
}
if (nPointsInVox) {
// process last voxel
VoxRes& resVox = secData[currVoxBin];
processVoxelResiduals(dyVec, dzVec, tgVec, resVox);
}
LOG(info) << "extracted residuals for sector " << iSec;
int nRowsOK = validateVoxels(iSec);
LOG(info) << "number of validated X rows: " << nRowsOK;
if (!nRowsOK) {
LOG(warning) << "sector " << iSec << ": all X-bins disabled, abandon smoothing";
return;
} else {
smooth(iSec);
}
// process dispersions
dyVec.clear();
tgVec.clear();
currVoxBin = -1;
nProcessed = 0;
nPointsInVox = 0;
while (nProcessed < binData.size()) {
int idx = binIndices[nProcessed];
if (currVoxBin != binData[idx]) {
if (nPointsInVox) {
VoxRes& resVox = secData[currVoxBin];
if (!getXBinIgnored(iSec, resVox.bvox[VoxX])) {
processVoxelDispersions(tgVec, dyVec, resVox);
}
}
currVoxBin = binData[idx];
nPointsInVox = 0;
dyVec.clear();
tgVec.clear();
}
dyVec.push_back(mLocalResidualsIn[idx].dy * param::MaxResid / 0x7fff);
tgVec.push_back(mLocalResidualsIn[idx].tgSlp * param::MaxTgSlp / 0x7fff);
++nPointsInVox;
++nProcessed;
}
if (nPointsInVox) {
// process last voxel
VoxRes& resVox = secData[currVoxBin];
if (!getXBinIgnored(iSec, resVox.bvox[VoxX])) {
processVoxelDispersions(tgVec, dyVec, resVox);
}
}
// smooth dispersions
for (int ix = 0; ix < mNXBins; ++ix) {
if (getXBinIgnored(iSec, ix)) {
continue;
}
for (int iz = 0; iz < mNZ2XBins; ++iz) {
for (int ip = 0; ip < mNY2XBins; ++ip) {
int voxBin = getGlbVoxBin(ix, ip, iz);
VoxRes& resVox = secData[voxBin];
getSmoothEstimate(iSec, resVox.stat[VoxX], resVox.stat[VoxF], resVox.stat[VoxZ], resVox.DS, 0x1 << VoxV);
}
}
}
LOG(info) << "Done processing residuals for sector " << iSec;
dumpResults(iSec);
}
//______________________________________________________________________________
void TrackResiduals::processVoxelResiduals(std::vector<float>& dy, std::vector<float>& dz, std::vector<float>& tg, VoxRes& resVox)
{
int nPoints = dy.size();
if (nPoints < mParams->minEntriesPerVoxel) {
LOG(debug) << "voxel " << getGlbVoxBin(resVox.bvox) << " is skipped due to too few entries (" << nPoints << " < " << mParams->minEntriesPerVoxel << ")";
return;
} else {
LOGF(debug, "Processing voxel %i with %i entries", getGlbVoxBin(resVox.bvox), nPoints);
}
std::array<float, 7> zResults;
resVox.flags = 0;
std::vector<size_t> indices(dz.size());
if (!o2::math_utils::LTMUnbinned(dz, indices, zResults, mParams->LTMCut)) {
LOG(debug) << "failed trimming input array for voxel " << getGlbVoxBin(resVox.bvox);
return;
}
if (!mParams->isBfieldZero) {
std::array<float, 2> res{0.f};
std::array<float, 3> err{0.f};
float sigMAD = fitPoly1Robust(tg, dy, res, err, mParams->LTMCut);
if (sigMAD < 0) {
LOG(debug) << "failed robust linear fit, sigMAD = " << sigMAD;
return;
}
float corrErr = err[0] * err[2];
corrErr = corrErr > 0 ? err[1] / std::sqrt(corrErr) : -999;
//
resVox.D[ResX] = -res[1];
resVox.D[ResY] = res[0];
resVox.D[ResZ] = zResults[1];
resVox.E[ResX] = std::sqrt(err[2]);
resVox.E[ResY] = std::sqrt(err[0]);
resVox.E[ResZ] = zResults[4];
resVox.EXYCorr = corrErr;
resVox.D[ResD] = resVox.dYSigMAD = sigMAD; // later will be overwritten by real dispersion
resVox.dZSigLTM = zResults[2];
} else {
// for B=0 we cannot disentangle radial distortions from distortions in y,
// so simply use average for dy as well and set distortion in X to zero
std::array<float, 7> yResults;
std::vector<size_t> indicesY(dy.size());
if (!o2::math_utils::LTMUnbinned(dy, indicesY, yResults, mParams->LTMCut)) {
LOG(debug) << "failed trimming input array for voxel " << getGlbVoxBin(resVox.bvox);
return;
}
resVox.D[ResX] = 0; // force to zero
resVox.D[ResY] = yResults[1];
resVox.D[ResZ] = zResults[1];
resVox.E[ResX] = 0;
resVox.E[ResY] = yResults[4];
resVox.E[ResZ] = zResults[4];
resVox.EXYCorr = 0;
resVox.D[ResD] = resVox.dYSigMAD = yResults[2];
resVox.dZSigLTM = zResults[2];
}
LOGF(debug, "D[0]=%.2f, D[1]=%.2f, D[2]=%.2f, E[0]=%.2f, E[1]=%.2f, E[2]=%.2f, EXYCorr=%.4f, dYSigMAD=%.3f, dZSigLTM=%.3f",
resVox.D[0], resVox.D[1], resVox.D[2], resVox.E[0], resVox.E[1], resVox.E[2], resVox.EXYCorr, resVox.dYSigMAD, resVox.dZSigLTM);
resVox.flags |= DistDone;
return;
}
void TrackResiduals::processVoxelDispersions(std::vector<float>& tg, std::vector<float>& dy, VoxRes& resVox)
{
size_t nPoints = tg.size();
LOG(debug) << "processing voxel dispersions for vox " << getGlbVoxBin(resVox.bvox) << " with " << nPoints << " points";
if (nPoints < 2) {
return;
}
for (size_t i = nPoints; i--;) {
dy[i] -= resVox.DS[ResY] - resVox.DS[ResX] * tg[i];
}
resVox.D[ResD] = getMAD2Sigma(dy);
resVox.E[ResD] = resVox.D[ResD] / sqrt(2.f * nPoints); // a la gaussioan RMS error (very crude)
resVox.flags |= DispDone;
}
//______________________________________________________________________________
int TrackResiduals::validateVoxels(int iSec)
{
// apply voxel validation cuts
// return number of good voxels for given sector
int cntMasked = 0; // number of voxels masked for any reason (either low statistics or bad fit)
int cntLowStat = 0; // number of voxels which were not processed due to too low statistics
mXBinsIgnore[iSec].reset();
std::vector<VoxRes>& secData = mVoxelResults[iSec];
int cntMaskedFit = 0;
int cntMaskedSigma = 0;
// find bad voxels in sector
for (int ix = 0; ix < mNXBins; ++ix) {
int cntValid = 0;
for (int ip = 0; ip < mNY2XBins; ++ip) {
for (int iz = 0; iz < mNZ2XBins; ++iz) {
int binGlb = getGlbVoxBin(ix, ip, iz);
VoxRes& resVox = secData[binGlb];
if ((resVox.flags & DistDone) == 0) {
++cntLowStat;
}
bool voxelOK = (resVox.flags & DistDone) && !(resVox.flags & Masked);
if (voxelOK) {
// check fit errors
if (resVox.E[ResY] * resVox.E[ResY] > mParams->maxFitErrY2 ||
resVox.E[ResX] * resVox.E[ResX] > mParams->maxFitErrX2 ||
fabs(resVox.EXYCorr) > mParams->maxFitCorrXY) {
voxelOK = false;
++cntMaskedFit;
}
// check raw distribution sigmas
if (resVox.dYSigMAD > mParams->maxSigY ||
resVox.dZSigLTM > mParams->maxSigZ) {
voxelOK = false;
++cntMaskedSigma;
}
}
if (voxelOK) {
++cntValid;
} else {
++cntMasked;
resVox.flags |= Masked;
}
} // loop over Z
} // loop over Y/X
mValidFracXBins[iSec][ix] = static_cast<float>(cntValid) / (mNY2XBins * mNZ2XBins);
LOGP(debug, "Sector {}: xBin {} has {} % of voxels valid. Total masked due to fit: {} ,and sigma: {}",
iSec, ix, mValidFracXBins[iSec][ix] * 100., cntMaskedFit, cntMaskedSigma);
} // loop over X
// mask X-bins which cannot be smoothed
short nBadReg = 0; // count bad regions (one or more consecutive bad X-bins)
std::array<short, param::NPadRows> badStart; // to store indices to the beginnings of the bad regions
std::array<short, param::NPadRows> badEnd; // to store indices to the end of the bad regions
bool prevBad = false;
float fracBadRows = 0.f;
for (int ix = 0; ix < mNXBins; ++ix) {
if (mValidFracXBins[iSec][ix] < mParams->minValidVoxFracDrift) {
LOG(debug) << "row " << ix << " is bad";
++fracBadRows;
if (prevBad) {
badEnd[nBadReg] = ix;
} else {
badStart[nBadReg] = ix;
badEnd[nBadReg] = ix;
prevBad = true;
}
} else {
if (prevBad) {
++nBadReg;
prevBad = false;
}
}
}
if (prevBad) {
++nBadReg;
}
fracBadRows /= mNXBins;
if (fracBadRows > mParams->maxFracBadRowsPerSector) {
LOG(warning) << "sector " << iSec << ": Fraction of bad X-bins: " << fracBadRows << " -> masking whole sector";
mXBinsIgnore[iSec].set();
} else {
for (int iBad = 0; iBad < nBadReg; ++iBad) {
LOG(debug) << "masking bad region " << iBad;
short badInReg = badEnd[iBad] - badStart[iBad] + 1;
short badInNextReg = iBad < (nBadReg - 1) ? badEnd[iBad] - badStart[iBad] + 1 : 0;
if (badInReg > mParams->maxBadXBinsToCover) {
// disable too large bad patches
for (int i = 0; i < badInReg; ++i) {
LOG(debug) << "disabling too large patch in bad region " << iBad << ", badStart(" << badStart[iBad] << "), i(" << i << ")";
mXBinsIgnore[iSec].set(badStart[iBad] + i);
}
}
if (badInNextReg > mParams->maxBadXBinsToCover && (badStart[iBad + 1] - badEnd[iBad] - 1) < mParams->minGoodXBinsToCover) {
// disable too small isolated good patches`
for (int i = badEnd[iBad] + 1; i < badStart[iBad + 1]; ++i) {
LOG(debug) << "disabling too small good patch before bad region " << iBad + 1 << ", badStart(" << badEnd[iBad] << "), badEnd(" << badStart[iBad + 1] << ")";
mXBinsIgnore[iSec].set(i);
}
}
}
if (nBadReg) {
if (mXBinsIgnore[iSec].test(badStart[0]) && badStart[0] < mParams->minGoodXBinsToCover) {
// 1st good patch is too small
for (int i = 0; i < badStart[0]; ++i) {
LOG(debug) << "disabling too small first good patch badStart(0), badEnd(" << badStart[0] << ")";
mXBinsIgnore[iSec].set(i);
}
}
if (mXBinsIgnore[iSec].test(badStart[nBadReg - 1]) && (mNXBins - badEnd[nBadReg - 1] - 1) < mParams->minGoodXBinsToCover) {
// last good patch is too small
for (int i = badEnd[nBadReg - 1] + 1; i < mNXBins; ++i) {
LOG(debug) << "disabling too small last good patch badStart(" << badEnd[nBadReg - 1] << "), badEnd(" << mNXBins << ")";
mXBinsIgnore[iSec].set(i);
}
}
}
}
//
int nMaskedRows = mXBinsIgnore[iSec].count();
LOGP(info, "Sector {}: out of {} voxels {} are masked. {} (low stat), {} (invalid fit) and {} (raw distrib sigma)",
iSec, mNVoxPerSector, cntMasked, cntLowStat, cntMaskedFit, cntMaskedSigma);
//
return mNXBins - nMaskedRows;
}
void TrackResiduals::smooth(int iSec)
{
std::vector<VoxRes>& secData = mVoxelResults[iSec];
for (int ix = 0; ix < mNXBins; ++ix) {
if (getXBinIgnored(iSec, ix)) {
continue;
}
for (int ip = 0; ip < mNY2XBins; ++ip) {
for (int iz = 0; iz < mNZ2XBins; ++iz) {
int voxBin = getGlbVoxBin(ix, ip, iz);
VoxRes& resVox = secData[voxBin];
resVox.flags &= ~SmoothDone;
bool res = getSmoothEstimate(resVox.bsec, resVox.stat[VoxX], resVox.stat[VoxF], resVox.stat[VoxZ], resVox.DS, (0x1 << VoxX | 0x1 << VoxF | 0x1 << VoxZ));
if (!res) {
mNSmoothingFailedBins[iSec]++;
} else {
resVox.flags |= SmoothDone;
}
}
}
}
// substract dX contribution to dZ
for (int ix = 0; ix < mNXBins; ++ix) {
if (getXBinIgnored(iSec, ix)) {
continue;
}
for (int ip = 0; ip < mNY2XBins; ++ip) {
for (int iz = 0; iz < mNZ2XBins; ++iz) {
int voxBin = getGlbVoxBin(ix, ip, iz);
VoxRes& resVox = secData[voxBin];
if (!(resVox.flags & SmoothDone)) {
continue;
}
// TODO: Usage of Z/X is bug???
float z2x = resVox.stat[VoxZ];
if (mDoAdhocCorrectionZ2X) {
//
const float z = z2x * resVox.stat[VoxX] - resVox.DS[ResZ];
const float x = resVox.stat[VoxX] - resVox.DS[ResX]; // is subration of DS[ResX] correct?
z2x = z / x;
}
resVox.DS[ResZ] += z2x * resVox.DS[ResX]; // remove slope*dX contribution from dZ
resVox.D[ResZ] += z2x * resVox.DS[ResX]; // remove slope*dX contribution from dZ
//
if (mAdhocScalingX[iSec >= 18] != 0) {
const float aDX = resVox.DS[ResX] * mAdhocScalingX[iSec >= 18];
resVox.D[ResX] += aDX;
resVox.DS[ResX] += aDX;
resVox.D[ResY] += aDX * resVox.stat[VoxF];
resVox.DS[ResY] += aDX * resVox.stat[VoxF];
resVox.D[ResZ] += aDX * z2x;
resVox.DS[ResZ] += aDX * z2x;
}
}
}
}
}
bool TrackResiduals::getSmoothEstimate(int iSec, float x, float p, float z, std::array<float, ResDim>& res, int whichDim)
{
// get smooth estimate for distortions for point in sector coordinates
/// \todo correct use of the symmetric matrix should speed up the code
std::array<int, VoxDim> minPointsDir{0}; // min number of points per direction
const float kTrialStep = 0.5;
std::array<bool, ResDim> doDim{false};
for (int i = 0; i < ResDim; ++i) {
doDim[i] = (whichDim & (0x1 << i)) > 0;
if (doDim[i]) {
res[i] = 0.f;
}
}
int matSize = sSmtLinDim;
for (int i = 0; i < VoxDim; ++i) {
minPointsDir[i] = 3; // for pol1 smoothing require at least 3 points
if (mSmoothPol2[i]) {
++minPointsDir[i];
++matSize;
}
}
int ix0, ip0, iz0;
findVoxel(x, p, iSec < SECTORSPERSIDE ? z : -z, ix0, ip0, iz0); // find nearest voxel
std::vector<VoxRes>& secData = mVoxelResults[iSec];
int binCenter = getGlbVoxBin(ix0, ip0, iz0); // global bin of nearest voxel
VoxRes& voxCenter = secData[binCenter]; // nearest voxel
LOG(debug) << "getting smooth estimate around voxel " << binCenter;
// cache
// \todo maybe a 1-D cache would be more efficient?
std::array<std::array<double, sMaxSmtDim*(sMaxSmtDim + 1) / 2>, ResDim> cmat;
int maxNeighb = 10 * 10 * 10;
std::vector<VoxRes*> currVox;
currVox.reserve(maxNeighb);
std::vector<float> currCache;
currCache.reserve(maxNeighb * VoxHDim);
std::array<int, VoxDim> maxTrials;
maxTrials[VoxZ] = mNZ2XBins / 2;
maxTrials[VoxF] = mNY2XBins / 2;
maxTrials[VoxX] = mParams->maxBadXBinsToCover * 2;
std::array<int, VoxDim> trial{0};
while (true) {
std::fill(mLastSmoothingRes.begin(), mLastSmoothingRes.end(), 0);
memset(&cmat[0][0], 0, sizeof(cmat));
int nbOK = 0; // accounted neighbours
float stepX = mStepKern[VoxX] * (1. + kTrialStep * trial[VoxX]);
float stepF = mStepKern[VoxF] * (1. + kTrialStep * trial[VoxF]);
float stepZ = mStepKern[VoxZ] * (1. + kTrialStep * trial[VoxZ]);
if (!(voxCenter.flags & DistDone) || (voxCenter.flags & Masked) || getXBinIgnored(iSec, ix0)) {
// closest voxel has no data -> increase smoothing step
stepX += kTrialStep * mStepKern[VoxX];
stepF += kTrialStep * mStepKern[VoxF];
stepZ += kTrialStep * mStepKern[VoxZ];
}
// effective kernel widths accounting for the increased bandwidth at the edges and missing data
float kWXI = getDXI(ix0) * mKernelWInv[VoxX] * mStepKern[VoxX] / stepX;
float kWFI = getDY2XI(ix0, ip0) * mKernelWInv[VoxF] * mStepKern[VoxF] / stepF;
float kWZI = getDZ2XI(iz0) * mKernelWInv[VoxZ] * mStepKern[VoxZ] / stepZ;
int iStepX = static_cast<int>(nearbyint(stepX + 0.5));
int iStepF = static_cast<int>(nearbyint(stepF + 0.5));
int iStepZ = static_cast<int>(nearbyint(stepZ + 0.5));
int ixMin = ix0 - iStepX;
int ixMax = ix0 + iStepX;
if (ixMin < 0) {
ixMin = 0;
ixMax = std::min(static_cast<int>(nearbyint(ix0 + stepX * mKernelScaleEdge[VoxX])), mNXBins - 1);
kWXI /= mKernelScaleEdge[VoxX];
}
if (ixMax >= mNXBins) {
ixMax = mNXBins - 1;
ixMin = std::max(static_cast<int>(nearbyint(ix0 - stepX * mKernelScaleEdge[VoxX])), 0);
kWXI /= mKernelScaleEdge[VoxX];
}
int ipMin = ip0 - iStepF;
int ipMax = ip0 + iStepF;
if (ipMin < 0) {
ipMin = 0;
ipMax = std::min(static_cast<int>(nearbyint(ip0 + stepF * mKernelScaleEdge[VoxF])), mNY2XBins - 1);
kWFI /= mKernelScaleEdge[VoxF];
}
if (ipMax >= mNY2XBins) {
ipMax = mNY2XBins - 1;
ipMin = std::max(static_cast<int>(nearbyint(ip0 - stepF * mKernelScaleEdge[VoxF])), 0);
kWFI /= mKernelScaleEdge[VoxF];
}
int izMin = iz0 - iStepZ;
int izMax = iz0 + iStepZ;
if (izMin < 0) {
izMin = 0;
izMax = std::min(static_cast<int>(nearbyint(iz0 + stepZ * mKernelScaleEdge[VoxZ])), mNZ2XBins - 1);
kWZI /= mKernelScaleEdge[VoxZ];
}
if (izMax >= mNZ2XBins) {
izMax = mNZ2XBins - 1;
izMin = std::max(static_cast<int>(nearbyint(iz0 - stepZ * mKernelScaleEdge[VoxZ])), 0);
kWZI /= mKernelScaleEdge[VoxZ];
}
std::vector<unsigned short> nOccX(ixMax - ixMin + 1, 0);
std::vector<unsigned short> nOccF(ipMax - ipMin + 1, 0);
std::vector<unsigned short> nOccZ(izMax - izMin + 1, 0);
int nbCheck = (ixMax - ixMin + 1) * (ipMax - ipMin + 1) * (izMax - izMin + 1);
if (nbCheck >= maxNeighb) {
maxNeighb = nbCheck + 100;
currCache.reserve(maxNeighb * VoxHDim);
currVox.reserve(maxNeighb);
}
std::array<double, 3> u2Vec;
// first loop, check presence of enough points
for (int ix = ixMin; ix <= ixMax; ++ix) {
for (int ip = ipMin; ip <= ipMax; ++ip) {
for (int iz = izMin; iz <= izMax; ++iz) {
int binNb = getGlbVoxBin(ix, ip, iz);
VoxRes& voxNb = secData[binNb];
if (!(voxNb.flags & DistDone) ||
(voxNb.flags & Masked) ||
getXBinIgnored(iSec, ix)) {
// skip voxels w/o data
continue;
}
// estimate weighted distance
float dx = voxNb.stat[VoxX] - x;
float df = voxNb.stat[VoxF] - p;
float dz = voxNb.stat[VoxZ] - z;
float dxw = dx * kWXI;
float dfw = df * kWFI;
float dzw = dz * kWZI;
u2Vec[0] = dxw * dxw;
u2Vec[1] = dfw * dfw;
u2Vec[2] = dzw * dzw;
double kernelWeight = getKernelWeight(u2Vec);
if (kernelWeight < 1e-6) {
continue;
}
// new point is validated
++nOccX[ix - ixMin];
++nOccF[ip - ipMin];
++nOccZ[iz - izMin];
currVox[nbOK] = &voxNb;
currCache[nbOK * VoxHDim + VoxX] = dx;
currCache[nbOK * VoxHDim + VoxF] = df;
currCache[nbOK * VoxHDim + VoxZ] = dz;
currCache[nbOK * VoxHDim + VoxV] = kernelWeight;
++nbOK;
}
}
}
// check if we have enough points in every dimension
std::array<int, VoxDim> nPoints{0};
for (int i = ixMax - ixMin + 1; i--;) {
if (nOccX[i]) {
++nPoints[VoxX];
}
}
for (int i = ipMax - ipMin + 1; i--;) {
if (nOccF[i]) {
++nPoints[VoxF];
}
}
for (int i = izMax - izMin + 1; i--;) {
if (nOccZ[i]) {
++nPoints[VoxZ];
}
}
bool enoughPoints = true;
std::array<bool, VoxDim> incrDone{false};
for (int i = 0; i < VoxDim; ++i) {
if (nPoints[i] < minPointsDir[i]) {
// need to extend smoothing neighbourhood
enoughPoints = false;
if (trial[i] < maxTrials[i] && !incrDone[i]) {
// try to increment only missing direction
++trial[i];
incrDone[i] = true;
} else if (trial[i] == maxTrials[i]) {
// cannot increment missing direction, try others
for (int j = VoxDim; j--;) {
if (i != j && trial[j] < maxTrials[j] && !incrDone[j]) {
++trial[j];
incrDone[j] = true;
}
}
}
}
}
if (!enoughPoints) {
if (!(incrDone[VoxX] || incrDone[VoxF] || incrDone[VoxZ])) {
LOG(error) << fmt::format("trial limit reached, skipping this voxel: incrDone[VoxX] {}, incrDone[VoxF] {}, incrDone[VoxZ] {}", incrDone[VoxX], incrDone[VoxF], incrDone[VoxZ]);
return false;
}
LOG(debug) << "sector " << iSec << ": increasing filter bandwidth around voxel " << binCenter;
// printf("Sector:%2d x=%.2f y/x=%.2f z/x=%.2f (iX: %d iY2X:%d iZ2X:%d)\n", iSec, x, p, z, ix0, ip0, iz0);
// printf("not enough neighbours (need min %d) %d %d %d (tot: %d) | Steps: %.1f %.1f %.1f\n", 2, nPoints[VoxX], nPoints[VoxF], nPoints[VoxZ], nbOK, stepX, stepF, stepZ);
// printf("trying to increase filter bandwidth (trialXFZ: %d %d %d)\n", trial[VoxX], trial[VoxF], trial[VoxZ]);
continue;
}
// now fill matrices and solve
for (int iNb = 0; iNb < nbOK; ++iNb) {
double wiCache = currCache[iNb * VoxHDim + VoxV];
double dxi = currCache[iNb * VoxHDim + VoxX];
double dfi = currCache[iNb * VoxHDim + VoxF];
double dzi = currCache[iNb * VoxHDim + VoxZ];
double dxi2 = dxi * dxi;
double dfi2 = dfi * dfi;
double dzi2 = dzi * dzi;
const VoxRes* voxNb = currVox[iNb];
for (int iDim = 0; iDim < ResDim; ++iDim) {
if (!doDim[iDim]) {
continue;
}
double vi = voxNb->D[iDim];
double wi = wiCache;
if (mUseErrInSmoothing && fabs(voxNb->E[iDim]) > 1e-6) {
// account for point error apart from kernel value
wi /= (voxNb->E[iDim] * voxNb->E[iDim]);
}
std::array<double, sMaxSmtDim*(sMaxSmtDim + 1) / 2>& cmatD = cmat[iDim];
double* rhsD = &mLastSmoothingRes[iDim * sMaxSmtDim];
unsigned short iMat = 0;
unsigned short iRhs = 0;
// linear part
cmatD[iMat++] += wi;
rhsD[iRhs++] += wi * vi;
//
cmatD[iMat++] += wi * dxi;
cmatD[iMat++] += wi * dxi2;
rhsD[iRhs++] += wi * dxi * vi;
//
cmatD[iMat++] += wi * dfi;
cmatD[iMat++] += wi * dxi * dfi;
cmatD[iMat++] += wi * dfi2;
rhsD[iRhs++] += wi * dfi * vi;
//
cmatD[iMat++] += wi * dzi;
cmatD[iMat++] += wi * dxi * dzi;
cmatD[iMat++] += wi * dfi * dzi;
cmatD[iMat++] += wi * dzi2;