forked from AliceO2Group/AliceO2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThresholdCalibratorSpec.cxx
More file actions
2042 lines (1824 loc) · 84.5 KB
/
ThresholdCalibratorSpec.cxx
File metadata and controls
2042 lines (1824 loc) · 84.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 ThresholdCalibratorSpec.cxx
#include "ITSWorkflow/ThresholdCalibratorSpec.h"
#include "CommonUtils/FileSystemUtils.h"
#include "CCDB/BasicCCDBManager.h"
#ifdef WITH_OPENMP
#include <omp.h>
#endif
namespace o2
{
namespace its
{
//////////////////////////////////////////////////////////////////////////////
// Define error function for ROOT fitting
double erf(double* xx, double* par)
{
return (nInjScaled / 2) * TMath::Erf((xx[0] - par[0]) / (sqrt(2) * par[1])) + (nInjScaled / 2);
}
// ITHR erf is reversed
double erf_ithr(double* xx, double* par)
{
return (nInjScaled / 2) * (1 - TMath::Erf((xx[0] - par[0]) / (sqrt(2) * par[1])));
}
//////////////////////////////////////////////////////////////////////////////
// Default constructor
ITSThresholdCalibrator::ITSThresholdCalibrator(const ITSCalibInpConf& inpConf)
: mChipModSel(inpConf.chipModSel), mChipModBase(inpConf.chipModBase)
{
mSelfName = o2::utils::Str::concat_string(ChipMappingITS::getName(), "ITSThresholdCalibrator");
}
//////////////////////////////////////////////////////////////////////////////
// Default deconstructor
ITSThresholdCalibrator::~ITSThresholdCalibrator()
{
// Clear dynamic memory
delete[] this->mX;
this->mX = nullptr;
if (this->mFitType == FIT) {
delete this->mFitHist;
this->mFitHist = nullptr;
delete this->mFitFunction;
this->mFitFunction = nullptr;
}
}
//////////////////////////////////////////////////////////////////////////////
void ITSThresholdCalibrator::init(InitContext& ic)
{
LOGF(info, "ITSThresholdCalibrator init...", mSelfName);
mPercentageCut = ic.options().get<short int>("percentage-cut");
mColStep = ic.options().get<short int>("s-curve-col-step");
if (mColStep >= N_COL) {
LOG(warning) << "mColStep = " << mColStep << ": saving s-curves of only 1 pixel (pix 0) per row";
}
std::string fittype = ic.options().get<std::string>("fittype");
if (fittype == "derivative") {
this->mFitType = DERIVATIVE;
} else if (fittype == "fit") {
this->mFitType = FIT;
} else if (fittype == "hitcounting") {
this->mFitType = HITCOUNTING;
} else {
LOG(error) << "fittype " << fittype
<< " not recognized, please use 'derivative', 'fit', or 'hitcounting'";
throw fittype;
}
// Get metafile directory from input
try {
this->mMetafileDir = ic.options().get<std::string>("meta-output-dir");
} catch (std::exception const& e) {
LOG(warning) << "Input parameter meta-output-dir not found"
<< "\n*** Setting metafile output directory to /dev/null";
}
if (this->mMetafileDir != "/dev/null") {
this->mMetafileDir = o2::utils::Str::rectifyDirectory(this->mMetafileDir);
}
// Get ROOT output directory from input
try {
this->mOutputDir = ic.options().get<std::string>("output-dir");
} catch (std::exception const& e) {
LOG(warning) << "Input parameter output-dir not found"
<< "\n*** Setting ROOT output directory to ./";
}
this->mOutputDir = o2::utils::Str::rectifyDirectory(this->mOutputDir);
// Get metadata data type from input
try {
this->mMetaType = ic.options().get<std::string>("meta-type");
} catch (std::exception const& e) {
LOG(warning) << "Input parameter meta-type not found"
<< "\n*** Disabling 'type' in metadata output files";
}
this->mVerboseOutput = ic.options().get<bool>("verbose");
// Get number of threads
this->mNThreads = ic.options().get<int>("nthreads");
// Check fit type vs nthreads (fit option is not thread safe!)
if (mFitType == FIT && mNThreads > 1) {
throw std::runtime_error("Multiple threads are requested with fit method which is not thread safe");
}
// Machine hostname
this->mHostname = boost::asio::ip::host_name();
// check flag to tag single noisy pix in digital and analog scans
this->mTagSinglePix = ic.options().get<bool>("enable-single-pix-tag");
// get min and max ithr and vcasn (default if not specified)
inMinVcasn = ic.options().get<short int>("min-vcasn");
inMaxVcasn = ic.options().get<short int>("max-vcasn");
inMinIthr = ic.options().get<short int>("min-ithr");
inMaxIthr = ic.options().get<short int>("max-ithr");
if (inMinVcasn > inMaxVcasn || inMinIthr > inMaxIthr) {
throw std::runtime_error("Min VCASN/ITHR is larger than Max VCASN/ITHR: check the settings, analysis not possible");
}
// Get flag to enable most-probable value calculation
isMpv = ic.options().get<bool>("enable-mpv");
// Parameters to operate in manual mode (when run type is not recognized automatically)
isManualMode = ic.options().get<bool>("manual-mode");
if (isManualMode) {
try {
manualRowScan = ic.options().get<short int>("manual-rowscan");
} catch (std::exception const& e) {
throw std::runtime_error("Number of scanned rows not found, mandatory in manual mode");
}
try {
manualMin = ic.options().get<short int>("manual-min");
} catch (std::exception const& e) {
throw std::runtime_error("Min value of the scan parameter not found, mandatory in manual mode");
}
try {
manualMax = ic.options().get<short int>("manual-max");
} catch (std::exception const& e) {
throw std::runtime_error("Max value of the scan parameter not found, mandatory in manual mode");
}
try {
manualScanType = ic.options().get<std::string>("manual-scantype");
} catch (std::exception const& e) {
throw std::runtime_error("Scan type not found, mandatory in manual mode");
}
try {
saveTree = ic.options().get<bool>("save-tree");
} catch (std::exception const& e) {
throw std::runtime_error("Please specify if you want to save the ROOT trees, mandatory in manual mode");
}
// this is not mandatory since it's 1 by default
manualStep = ic.options().get<short int>("manual-step");
// this is not mandatory since it's 0 by default
manualMin2 = ic.options().get<short int>("manual-min2");
// this is not mandatory since it's 0 by default
manualMax2 = ic.options().get<short int>("manual-max2");
// this is not mandatory since it's 1 by default
manualStep2 = ic.options().get<short int>("manual-step2");
// this is not mandatory since it's 5 by default
manualStrobeWindow = ic.options().get<short int>("manual-strobewindow");
// Flag to scale the number of injections by 3 in case --meb-select is used
scaleNinj = ic.options().get<bool>("scale-ninj");
}
// Flag to enable the analysis of CRU_ITS data
isCRUITS = ic.options().get<bool>("enable-cru-its");
// Number of injections
nInj = ic.options().get<int>("ninj");
nInjScaled = nInj;
// flag to set the url ccdb mgr
this->mCcdbMgrUrl = ic.options().get<std::string>("ccdb-mgr-url");
// FIXME: Temporary solution to retrieve ConfDBmap
long int ts = o2::ccdb::getCurrentTimestamp();
LOG(info) << "Getting confDB map from ccdb - timestamp: " << ts;
auto& mgr = o2::ccdb::BasicCCDBManager::instance();
mgr.setURL(mCcdbMgrUrl);
mgr.setTimestamp(ts);
mConfDBmap = mgr.get<std::vector<int>>("ITS/Calib/Confdbmap");
// Parameters to dump s-curves on disk
isDumpS = ic.options().get<bool>("dump-scurves");
maxDumpS = ic.options().get<int>("max-dump");
chipDumpS = ic.options().get<std::string>("chip-dump"); // comma-separated list of chips
chipDumpList = getIntegerVect(chipDumpS);
if (isDumpS && mFitType != FIT) {
LOG(error) << "S-curve dump enabled but `fittype` is not fit. Please check";
}
if (isDumpS) {
fileDumpS = TFile::Open(Form("s-curves_%d.root", mChipModSel), "RECREATE"); // in case of multiple processes, every process will have it's own file
if (maxDumpS < 0) {
LOG(info) << "`max-dump` " << maxDumpS << ". Dumping all s-curves";
} else {
LOG(info) << "`max-dump` " << maxDumpS << ". Dumping " << maxDumpS << " s-curves";
}
if (!chipDumpList.size()) {
LOG(info) << "Dumping s-curves for all chips";
} else {
LOG(info) << "Dumping s-curves for chips: " << chipDumpS;
}
}
// flag to enable the calculation of the slope in 2d pulse shape scans
doSlopeCalculation = ic.options().get<bool>("calculate-slope");
if (doSlopeCalculation) {
try {
chargeA = ic.options().get<int>("charge-a");
} catch (std::exception const& e) {
throw std::runtime_error("You want to do the slop calculation but you did not specify charge-a");
}
try {
chargeB = ic.options().get<int>("charge-b");
} catch (std::exception const& e) {
throw std::runtime_error("You want to do the slop calculation but you did not specify charge-b");
}
}
// Variable to select from which multi-event buffer select the hits
mMeb = ic.options().get<int>("meb-select");
if (mMeb > 2) {
LOG(error) << "MEB cannot be greater than 2. Please check your command line.";
}
return;
}
//////////////////////////////////////////////////////////////////////////////
// Get number of active links for a given RU
short int ITSThresholdCalibrator::getNumberOfActiveLinks(bool* links)
{
int nL = 0;
for (int i = 0; i < 3; i++) {
if (links[i]) {
nL++;
}
}
return nL;
}
//////////////////////////////////////////////////////////////////////////////
// Get link ID: 0,1,2 for IB RUs / 0,1 for OB RUs
short int ITSThresholdCalibrator::getLinkID(short int chipID, short int ruID)
{
if (chipID < 432) {
return (chipID - ruID * 9) / 3;
} else if (chipID >= 432 && chipID < 6480) {
return (chipID - 48 * 9 - (ruID - 48) * 112) / 56;
} else {
return (chipID - 48 * 9 - 54 * 112 - (ruID - 102) * 196) / 98;
}
}
//////////////////////////////////////////////////////////////////////////////
// Get list of chipID (from 0 to 24119) attached to a RU based on the links which are active
std::vector<short int> ITSThresholdCalibrator::getChipListFromRu(short int ruID, bool* links)
{
std::vector<short int> cList;
int a, b;
if (ruID < 48) {
a = ruID * 9;
b = a + 9 - 1;
} else if (ruID >= 48 && ruID < 102) {
a = 48 * 9 + (ruID - 48) * 112;
b = a + 112 - 1;
} else {
a = 48 * 9 + 54 * 112 + (ruID - 102) * 196;
b = a + 196 - 1;
}
for (int c = a; c <= b; c++) {
short int lid = getLinkID(c, ruID);
if (links[lid]) {
cList.push_back(c);
}
}
return cList;
}
//////////////////////////////////////////////////////////////////////////////
// Get RU ID (from 0 to 191) from a given O2ChipID (from 0 to 24119)
short int ITSThresholdCalibrator::getRUID(short int chipID)
{
// below there are the inverse of the formulas in getChipListFromRu(...)
if (chipID < 432) { // IB
return chipID / 9;
} else if (chipID >= 432 && chipID < 6480) { // ML
return (chipID - 48 * 9 + 112 * 48) / 112;
} else { // OL
return (chipID - 48 * 9 - 54 * 112 + 102 * 196) / 196;
}
}
//////////////////////////////////////////////////////////////////////////////
// Convert comma-separated list of integers to a vector of int
std::vector<short int> ITSThresholdCalibrator::getIntegerVect(std::string& s)
{
std::stringstream ss(s);
std::vector<short int> result;
char ch;
short int tmp;
while (ss >> tmp) {
result.push_back(tmp);
ss >> ch;
}
return result;
}
//////////////////////////////////////////////////////////////////////////////
// Open a new ROOT file and threshold TTree for that file
void ITSThresholdCalibrator::initThresholdTree(bool recreate /*=true*/)
{
// Create output directory to store output
std::string dir = this->mOutputDir + fmt::format("{}_{}/", mDataTakingContext.envId, mDataTakingContext.runNumber);
o2::utils::createDirectoriesIfAbsent(dir);
LOG(info) << "Created " << dir << " directory for ROOT trees output";
std::string filename = dir + mDataTakingContext.runNumber + '_' +
std::to_string(this->mFileNumber) + '_' + this->mHostname + "_modSel" + std::to_string(mChipModSel) + ".root.part";
// Check if file already exists
struct stat buffer;
if (recreate && stat(filename.c_str(), &buffer) == 0) {
LOG(warning) << "File " << filename << " already exists, recreating";
}
// Initialize ROOT output file
// to prevent premature external usage, use temporary name
const char* option = recreate ? "RECREATE" : "UPDATE";
mRootOutfile = new TFile(filename.c_str(), option);
// Tree containing the s-curves points
mScTree = new TTree("s-curve-points", "s-curve-points");
mScTree->Branch("chipid", &vChipid, "vChipID[1024]/S");
mScTree->Branch("row", &vRow, "vRow[1024]/S");
// Initialize output TTree branches
mThresholdTree = new TTree("ITS_calib_tree", "ITS_calib_tree");
mThresholdTree->Branch("chipid", &vChipid, "vChipID[1024]/S");
mThresholdTree->Branch("row", &vRow, "vRow[1024]/S");
if (mScanType == 'T' || mScanType == 'V' || mScanType == 'I') {
std::string bName = mScanType == 'T' ? "thr" : mScanType == 'V' ? "vcasn"
: "ithr";
mThresholdTree->Branch(bName.c_str(), &vThreshold, "vThreshold[1024]/S");
mThresholdTree->Branch("noise", &vNoise, "vNoise[1024]/F");
mThresholdTree->Branch("spoints", &vPoints, "vPoints[1024]/b");
mThresholdTree->Branch("success", &vSuccess, "vSuccess[1024]/O");
mScTree->Branch("chg", &vCharge, "vCharge[1024]/b");
mScTree->Branch("hits", &vHits, "vHits[1024]/b");
} else if (mScanType == 'D' || mScanType == 'A') { // this->mScanType == 'D' and this->mScanType == 'A'
mThresholdTree->Branch("n_hits", &vThreshold, "vThreshold[1024]/S");
} else if (mScanType == 'P') {
mThresholdTree->Branch("n_hits", &vThreshold, "vThreshold[1024]/S");
mThresholdTree->Branch("strobedel", &vMixData, "vMixData[1024]/S");
} else if (mScanType == 'p' || mScanType == 't') {
mThresholdTree->Branch("n_hits", &vThreshold, "vThreshold[1024]/S");
mThresholdTree->Branch("strobedel", &vMixData, "vMixData[1024]/S");
mThresholdTree->Branch("charge", &vCharge, "vCharge[1024]/b");
if (doSlopeCalculation) {
mSlopeTree = new TTree("line_tree", "line_tree");
mSlopeTree->Branch("chipid", &vChipid, "vChipID[1024]/S");
mSlopeTree->Branch("row", &vRow, "vRow[1024]/S");
mSlopeTree->Branch("slope", &vSlope, "vSlope[1024]/F");
mSlopeTree->Branch("intercept", &vIntercept, "vIntercept[1024]/F");
}
} else if (mScanType == 'R') {
mThresholdTree->Branch("n_hits", &vThreshold, "vThreshold[1024]/S");
mThresholdTree->Branch("vresetd", &vMixData, "vMixData[1024]/S");
} else if (mScanType == 'r') {
mThresholdTree->Branch("thr", &vThreshold, "vThreshold[1024]/S");
mThresholdTree->Branch("noise", &vNoise, "vNoise[1024]/F");
mThresholdTree->Branch("success", &vSuccess, "vSuccess[1024]/O");
mThresholdTree->Branch("vresetd", &vMixData, "vMixData[1024]/S");
}
return;
}
//////////////////////////////////////////////////////////////////////////////
// Returns upper / lower limits for threshold determination.
// data is the number of trigger counts per charge injected;
// x is the array of charge injected values;
// NPoints is the length of both arrays.
bool ITSThresholdCalibrator::findUpperLower(
std::vector<std::vector<unsigned short int>> data, const short int& NPoints,
short int& lower, short int& upper, bool flip, int iloop2)
{
// Initialize (or re-initialize) upper and lower
upper = -1;
lower = -1;
if (flip) { // ITHR case. lower is at large mX[i], upper is at small mX[i]
for (int i = 0; i < NPoints; i++) {
int comp = mScanType != 'r' ? data[iloop2][i] : data[i][iloop2];
if (comp == 0) {
upper = i;
break;
}
}
if (upper == -1) {
return false;
}
for (int i = upper; i > 0; i--) {
int comp = mScanType != 'r' ? data[iloop2][i] : data[i][iloop2];
if (comp >= nInjScaled) {
lower = i;
break;
}
}
} else { // not flipped
for (int i = 0; i < NPoints; i++) {
int comp = mScanType != 'r' ? data[iloop2][i] : data[i][iloop2];
if (comp >= nInjScaled) {
upper = i;
break;
}
}
if (upper == -1) {
return false;
}
for (int i = upper; i > 0; i--) {
int comp = mScanType != 'r' ? data[iloop2][i] : data[i][iloop2];
if (comp == 0) {
lower = i;
break;
}
}
}
// If search was successful, return central x value
if ((lower == -1) || (upper < lower)) {
return false;
}
return true;
}
//////////////////////////////////////////////////////////////////////////////
// Main findThreshold function which calls one of the three methods
bool ITSThresholdCalibrator::findThreshold(
const short int& chipID, std::vector<std::vector<unsigned short int>> data, const float* x, short int& NPoints,
float& thresh, float& noise, int& spoints, int iloop2)
{
bool success = false;
switch (this->mFitType) {
case DERIVATIVE: // Derivative method
success = this->findThresholdDerivative(data, x, NPoints, thresh, noise, spoints, iloop2);
break;
case FIT: // Fit method
success = this->findThresholdFit(chipID, data, x, NPoints, thresh, noise, spoints, iloop2);
break;
case HITCOUNTING: // Hit-counting method
success = this->findThresholdHitcounting(data, x, NPoints, thresh, iloop2);
// noise = 0;
break;
}
return success;
}
//////////////////////////////////////////////////////////////////////////////
// Use ROOT to find the threshold and noise via S-curve fit
// data is the number of trigger counts per charge injected;
// x is the array of charge injected values;
// NPoints is the length of both arrays.
// thresh, noise, chi2 pointers are updated with results from the fit
// spoints: number of points in the S of the S-curve (with n_hits between 0 and 50, excluding first and last point)
// iloop2 is 0 for thr scan but is equal to vresetd index in 2D vresetd scan
bool ITSThresholdCalibrator::findThresholdFit(
const short int& chipID, std::vector<std::vector<unsigned short int>> data, const float* x, const short int& NPoints,
float& thresh, float& noise, int& spoints, int iloop2)
{
// Find lower & upper values of the S-curve region
short int lower, upper;
bool flip = (this->mScanType == 'I');
auto fndVal = std::find(chipDumpList.begin(), chipDumpList.end(), chipID);
if (!this->findUpperLower(data, NPoints, lower, upper, flip, iloop2) || lower == upper) {
if (this->mVerboseOutput) {
LOG(warning) << "Start-finding unsuccessful: (lower, upper) = ("
<< lower << ", " << upper << ")";
}
if (isDumpS && (dumpCounterS[chipID] < maxDumpS || maxDumpS < 0) && (fndVal != chipDumpList.end() || !chipDumpList.size())) { // save bad s-curves
for (int i = 0; i < NPoints; i++) {
this->mFitHist->SetBinContent(i + 1, mScanType != 'r' ? data[iloop2][i] : data[i][iloop2]);
}
fileDumpS->cd();
mFitHist->Write();
}
if (isDumpS) {
dumpCounterS[chipID]++;
}
return false;
}
float start = (this->mX[upper] + this->mX[lower]) / 2;
if (start < 0) {
if (this->mVerboseOutput) {
LOG(warning) << "Start-finding unsuccessful: Start = " << start;
}
return false;
}
for (int i = 0; i < NPoints; i++) {
this->mFitHist->SetBinContent(i + 1, mScanType != 'r' ? data[iloop2][i] : data[i][iloop2]);
}
// Initialize starting parameters
this->mFitFunction->SetParameter(0, start);
this->mFitFunction->SetParameter(1, 8);
this->mFitHist->Fit("mFitFunction", "RQL");
if (isDumpS && (dumpCounterS[chipID] < maxDumpS || maxDumpS < 0) && (fndVal != chipDumpList.end() || !chipDumpList.size())) { // save good s-curves
fileDumpS->cd();
mFitHist->Write();
}
if (isDumpS) {
dumpCounterS[chipID]++;
}
noise = this->mFitFunction->GetParameter(1);
thresh = this->mFitFunction->GetParameter(0);
float chi2 = this->mFitFunction->GetChisquare() / this->mFitFunction->GetNDF();
spoints = upper - lower - 1;
// Clean up histogram for next time it is used
this->mFitHist->Reset();
return (chi2 < 5);
}
//////////////////////////////////////////////////////////////////////////////
// Use ROOT to find the threshold and noise via derivative method
// data is the number of trigger counts per charge injected;
// x is the array of charge injected values;
// NPoints is the length of both arrays.
// spoints: number of points in the S of the S-curve (with n_hits between 0 and 50, excluding first and last point)
// iloop2 is 0 for thr scan but is equal to vresetd index in 2D vresetd scan
bool ITSThresholdCalibrator::findThresholdDerivative(std::vector<std::vector<unsigned short int>> data, const float* x, const short int& NPoints,
float& thresh, float& noise, int& spoints, int iloop2)
{
// Find lower & upper values of the S-curve region
short int lower, upper;
bool flip = (this->mScanType == 'I');
if (!this->findUpperLower(data, NPoints, lower, upper, flip, iloop2) || lower == upper) {
if (this->mVerboseOutput) {
LOG(warning) << "Start-finding unsuccessful: (lower, upper) = (" << lower << ", " << upper << ")";
}
return false;
}
int deriv_size = upper - lower;
float deriv[deriv_size];
float xfx = 0, fx = 0;
// Fill array with derivatives
for (int i = lower; i < upper; i++) {
deriv[i - lower] = std::abs(mScanType != 'r' ? (data[iloop2][i + 1] - data[iloop2][i]) : (data[i + 1][iloop2] - data[i][iloop2])) / (this->mX[i + 1] - mX[i]);
xfx += this->mX[i] * deriv[i - lower];
fx += deriv[i - lower];
}
if (fx > 0.) {
thresh = xfx / fx;
}
float stddev = 0;
for (int i = lower; i < upper; i++) {
stddev += std::pow(this->mX[i] - thresh, 2) * deriv[i - lower];
}
stddev /= fx;
noise = std::sqrt(stddev);
spoints = upper - lower - 1;
return fx > 0.;
}
//////////////////////////////////////////////////////////////////////////////
// Use ROOT to find the threshold and noise via derivative method
// data is the number of trigger counts per charge injected;
// x is the array of charge injected values;
// NPoints is the length of both arrays.
// iloop2 is 0 for thr scan but is equal to vresetd index in 2D vresetd scan
bool ITSThresholdCalibrator::findThresholdHitcounting(
std::vector<std::vector<unsigned short int>> data, const float* x, const short int& NPoints, float& thresh, int iloop2)
{
unsigned short int numberOfHits = 0;
bool is50 = false;
for (unsigned short int i = 0; i < NPoints; i++) {
numberOfHits += (mScanType != 'r') ? data[iloop2][i] : data[i][iloop2];
int comp = (mScanType != 'r') ? data[iloop2][i] : data[i][iloop2];
if (!is50 && comp == nInjScaled) {
is50 = true;
}
}
// If not enough counts return a failure
if (!is50) {
if (this->mVerboseOutput) {
LOG(warning) << "Calculation unsuccessful: too few hits. Skipping this pixel";
}
return false;
}
if (this->mScanType == 'T') {
thresh = this->mX[N_RANGE - 1] - numberOfHits / float(nInjScaled);
} else if (this->mScanType == 'V') {
thresh = (this->mX[N_RANGE - 1] * nInjScaled - numberOfHits) / float(nInjScaled);
} else if (this->mScanType == 'I') {
thresh = (numberOfHits + nInjScaled * this->mX[0]) / float(nInjScaled);
} else {
LOG(error) << "Unexpected runtype encountered in findThresholdHitcounting()";
return false;
}
return true;
}
//////////////////////////////////////////////////////////////////////////////
// Run threshold extraction on completed row and update memory
void ITSThresholdCalibrator::extractThresholdRow(const short int& chipID, const short int& row)
{
if (this->mScanType == 'D' || this->mScanType == 'A') {
// Loop over all columns (pixels) in the row
for (short int col_i = 0; col_i < this->N_COL; col_i++) {
vChipid[col_i] = chipID;
vRow[col_i] = row;
vThreshold[col_i] = this->mPixelHits[chipID][row][col_i][0][0];
if (vThreshold[col_i] > nInj) {
this->mNoisyPixID[chipID].push_back(col_i * 1000 + row);
} else if (vThreshold[col_i] > 0 && vThreshold[col_i] < nInj) {
this->mIneffPixID[chipID].push_back(col_i * 1000 + row);
} else if (vThreshold[col_i] == 0) {
this->mDeadPixID[chipID].push_back(col_i * 1000 + row);
}
}
} else if (this->mScanType == 'P' || this->mScanType == 'p' || mScanType == 'R' || mScanType == 't') {
// Loop over all columns (pixels) in the row
for (short int var1_i = 0; var1_i < this->N_RANGE; var1_i++) {
for (short int chg_i = 0; chg_i < this->N_RANGE2; chg_i++) {
for (short int col_i = 0; col_i < this->N_COL; col_i++) {
vChipid[col_i] = chipID;
vRow[col_i] = row;
vThreshold[col_i] = this->mPixelHits[chipID][row][col_i][chg_i][var1_i];
vMixData[col_i] = (var1_i * this->mStep) + mMin;
if (mScanType != 'R') {
vMixData[col_i]++; // +1 because a delay of n correspond to a real delay of n+1 (from ALPIDE manual)
}
vCharge[col_i] = (unsigned char)(chg_i * this->mStep2 + mMin2);
}
this->saveThreshold();
}
}
if (doSlopeCalculation) {
int delA = -1, delB = -1;
for (short int col_i = 0; col_i < this->N_COL; col_i++) {
for (short int chg_i = 0; chg_i < 2; chg_i++) {
bool isFound = false;
int checkchg = !chg_i ? chargeA / mStep2 : chargeB / mStep2;
for (short int sdel_i = N_RANGE - 1; sdel_i >= 0; sdel_i--) {
if (mPixelHits[chipID][row][col_i][checkchg - 1][sdel_i] == nInj) {
if (!chg_i) {
delA = mMin + sdel_i * mStep + mStep / 2;
isFound = true;
} else {
delB = mMin + sdel_i * mStep + mStep / 2;
isFound = true;
}
break;
}
} // end loop on strobe delays
if (!isFound) { // if not found, take the first point with hits starting from the left (i.e. in principle the closest point to the one with MAX n_hits)
for (short int sdel_i = 0; sdel_i < N_RANGE; sdel_i++) {
if (mPixelHits[chipID][row][col_i][checkchg - 1][sdel_i] > 0) {
if (!chg_i) {
delA = mMin + sdel_i * mStep + mStep / 2;
} else {
delB = mMin + sdel_i * mStep + mStep / 2;
}
break;
}
} // end loop on strobe delays
} // end if on isFound
} // end loop on the two charges
if (delA > 0 && delB > 0 && delA != delB) {
vSlope[col_i] = ((float)(chargeA - chargeB) / (float)(delA - delB));
vIntercept[col_i] = (float)chargeA - (float)(vSlope[col_i] * delA);
if (vSlope[col_i] < 0) { // protection for non expected slope
vSlope[col_i] = 0.;
vIntercept[col_i] = 0.;
}
} else {
vSlope[col_i] = 0.;
vIntercept[col_i] = 0.;
}
} // end loop on pix
mSlopeTree->Fill();
}
} else { // threshold, vcasn, ithr, vresetd_2d
for (int scan_i = 0; scan_i < ((mScanType == 'r') ? N_RANGE : N_RANGE2); scan_i++) {
#ifdef WITH_OPENMP
omp_set_num_threads(mNThreads);
#pragma omp parallel for schedule(dynamic)
#endif
// Loop over all columns (pixels) in the row
for (short int col_i = 0; col_i < this->N_COL; col_i++) {
// Do the threshold fit
float thresh = 0., noise = 0.;
bool success = false;
int spoints = 0;
if (isDumpS) { // already protected for multi-thread in the init
mFitHist->SetName(Form("scurve_chip%d_row%d_col%d_scani%d", chipID, row, col_i, scan_i));
}
success = this->findThreshold(chipID, mPixelHits[chipID][row][col_i],
this->mX, mScanType == 'r' ? N_RANGE2 : N_RANGE, thresh, noise, spoints, scan_i);
vChipid[col_i] = chipID;
vRow[col_i] = row;
vThreshold[col_i] = (mScanType == 'T' || mScanType == 'r') ? (short int)(thresh * 10.) : (short int)(thresh);
vNoise[col_i] = (float)(noise * 10.); // always factor 10 also for ITHR/VCASN to not have all zeros
vSuccess[col_i] = success;
vPoints[col_i] = spoints > 0 ? (unsigned char)(spoints) : 0;
if (mScanType == 'r') {
vMixData[col_i] = (scan_i * mStep) + mMin;
}
}
if (mScanType == 'r') {
this->saveThreshold(); // save before moving to the next vresetd
}
}
// Fill the ScTree tree
if (mScanType == 'T' || mScanType == 'V' || mScanType == 'I') { // TODO: store also for other scans?
for (int ichg = mMin; ichg <= mMax; ichg += mStep) {
for (short int col_i = 0; col_i < this->N_COL; col_i += mColStep) {
vCharge[col_i] = ichg;
vHits[col_i] = mPixelHits[chipID][row][col_i][0][(ichg - mMin) / mStep];
}
mScTree->Fill();
}
}
} // end of the else
// Saves threshold information to internal memory
if (mScanType != 'P' && mScanType != 'p' && mScanType != 't' && mScanType != 'R' && mScanType != 'r') {
if (mVerboseOutput) {
LOG(info) << "Saving data of ChipID: " << chipID << " Row: " << row;
}
this->saveThreshold();
}
}
//////////////////////////////////////////////////////////////////////////////
void ITSThresholdCalibrator::saveThreshold()
{
// write to TTree
this->mThresholdTree->Fill();
if (this->mScanType == 'V' || this->mScanType == 'I' || this->mScanType == 'T') {
// Save info in a map for later averaging
int sumT = 0, sumSqT = 0, sumN = 0, sumSqN = 0;
int countSuccess = 0, countUnsuccess = 0;
for (int i = 0; i < this->N_COL; i++) {
if (vSuccess[i]) {
sumT += vThreshold[i];
sumN += (int)vNoise[i];
sumSqT += (vThreshold[i]) * (vThreshold[i]);
sumSqN += ((int)vNoise[i]) * ((int)vNoise[i]);
countSuccess++;
if (vThreshold[i] >= mMin && vThreshold[i] <= mMax && (mScanType == 'I' || mScanType == 'V')) {
mpvCounter[vChipid[0]][vThreshold[i] - mMin]++;
}
} else {
countUnsuccess++;
}
}
short int chipID = vChipid[0];
std::array<long int, 6> dataSum{{sumT, sumSqT, sumN, sumSqN, countSuccess, countUnsuccess}};
if (!(this->mThresholds.count(chipID))) {
this->mThresholds[chipID] = dataSum;
} else {
std::array<long int, 6> dataAll{{this->mThresholds[chipID][0] + dataSum[0], this->mThresholds[chipID][1] + dataSum[1], this->mThresholds[chipID][2] + dataSum[2], this->mThresholds[chipID][3] + dataSum[3], this->mThresholds[chipID][4] + dataSum[4], this->mThresholds[chipID][5] + dataSum[5]}};
this->mThresholds[chipID] = dataAll;
}
}
return;
}
//////////////////////////////////////////////////////////////////////////////
// Perform final operations on output objects. In the case of a full threshold
// scan, rename ROOT file and create metadata file for writing to EOS
void ITSThresholdCalibrator::finalizeOutput()
{
// Check that objects actually exist in memory
if (!(mScTree) || !(this->mRootOutfile) || !(this->mThresholdTree) || (doSlopeCalculation && !(this->mSlopeTree))) {
return;
}
// Ensure that everything has been written to the ROOT file
this->mRootOutfile->cd();
this->mThresholdTree->Write(nullptr, TObject::kOverwrite);
this->mScTree->Write(nullptr, TObject::kOverwrite);
if (doSlopeCalculation) {
this->mSlopeTree->Write(nullptr, TObject::kOverwrite);
}
// Clean up the mThresholdTree, mScTree and ROOT output file
delete this->mThresholdTree;
this->mThresholdTree = nullptr;
delete mScTree;
mScTree = nullptr;
if (doSlopeCalculation) {
delete this->mSlopeTree;
this->mSlopeTree = nullptr;
}
this->mRootOutfile->Close();
delete this->mRootOutfile;
this->mRootOutfile = nullptr;
// Check that expected output directory exists
std::string dir = this->mOutputDir + fmt::format("{}_{}/", mDataTakingContext.envId, mDataTakingContext.runNumber);
if (!std::filesystem::exists(dir)) {
LOG(error) << "Cannot find expected output directory " << dir;
return;
}
// Expected ROOT output filename
std::string filename = mDataTakingContext.runNumber + '_' +
std::to_string(this->mFileNumber) + '_' + this->mHostname + "_modSel" + std::to_string(mChipModSel);
std::string filenameFull = dir + filename;
try {
std::rename((filenameFull + ".root.part").c_str(),
(filenameFull + ".root").c_str());
} catch (std::exception const& e) {
LOG(error) << "Failed to rename ROOT file " << filenameFull
<< ".root.part, reason: " << e.what();
}
// Create metadata file
o2::dataformats::FileMetaData* mdFile = new o2::dataformats::FileMetaData();
mdFile->fillFileData(filenameFull + ".root");
mdFile->setDataTakingContext(mDataTakingContext);
if (!(this->mMetaType.empty())) {
mdFile->type = this->mMetaType;
}
mdFile->priority = "high";
mdFile->lurl = filenameFull + ".root";
auto metaFileNameTmp = fmt::format("{}{}.tmp", this->mMetafileDir, filename);
auto metaFileName = fmt::format("{}{}.done", this->mMetafileDir, filename);
try {
std::ofstream metaFileOut(metaFileNameTmp);
metaFileOut << mdFile->asString() << '\n';
metaFileOut.close();
std::filesystem::rename(metaFileNameTmp, metaFileName);
} catch (std::exception const& e) {
LOG(error) << "Failed to create threshold metadata file "
<< metaFileName << ", reason: " << e.what();
}
delete mdFile;
// Next time a file is created, use a larger number
this->mFileNumber++;
return;
} // finalizeOutput
//////////////////////////////////////////////////////////////////////////////
// Set the run_type for this run
// Initialize the memory needed for this specific type of run
void ITSThresholdCalibrator::setRunType(const short int& runtype)
{
// Save run type info for future evaluation
this->mRunType = runtype;
if (runtype == THR_SCAN) {
// full_threshold-scan -- just extract thresholds for each pixel and write to TTree
// 512 rows per chip
this->mScanType = 'T';
this->initThresholdTree();
this->mMin = 0;
this->mMax = 50;
this->N_RANGE = 51;
this->mCheckExactRow = true;
mRowScan = 512;
} else if (runtype == THR_SCAN_SHORT || runtype == THR_SCAN_SHORT_100HZ ||
runtype == THR_SCAN_SHORT_200HZ || runtype == THR_SCAN_SHORT_33 || runtype == THR_SCAN_SHORT_2_10HZ || runtype == THR_SCAN_SHORT_150INJ) {
// threshold_scan_short -- just extract thresholds for each pixel and write to TTree
// 10 rows per chip
this->mScanType = 'T';
this->initThresholdTree();
this->mMin = 0;
this->mMax = 50;
this->N_RANGE = 51;
this->mCheckExactRow = true;
if (runtype == THR_SCAN_SHORT_150INJ) {
nInj = 150;
if (mMeb >= 0) {
nInjScaled = nInj / 3;
}
}
mRowScan = 11;
if (runtype == THR_SCAN_SHORT_33) {
mRowScan = 33;
} else if (runtype == THR_SCAN_SHORT_2_10HZ) {
mRowScan = 2;
}
} else if (runtype == VCASN150 || runtype == VCASN100 || runtype == VCASN100_100HZ || runtype == VCASN130 || runtype == VCASNBB) {
// VCASN tuning for different target thresholds
// Store average VCASN for each chip into CCDB
// ATTENTION: with back bias (VCASNBB) put max vcasn to 130 (default is 80)
// 4 rows per chip
this->mScanType = 'V';
this->initThresholdTree();
this->mMin = inMinVcasn; // 30 is the default
this->mMax = inMaxVcasn; // 80 is the default
this->N_RANGE = mMax - mMin + 1;
this->mCheckExactRow = true;
mRowScan = 4;
} else if (runtype == ITHR150 || runtype == ITHR100 || runtype == ITHR100_100HZ || runtype == ITHR130) {
// ITHR tuning -- average ITHR per chip
// S-curve is backwards from VCASN case, otherwise same
// 4 rows per chip
this->mScanType = 'I';
this->initThresholdTree();
this->mMin = inMinIthr; // 25 is the default
this->mMax = inMaxIthr; // 100 is the default
this->N_RANGE = mMax - mMin + 1;
this->mCheckExactRow = true;
mRowScan = 4;
} else if (runtype == DIGITAL_SCAN || runtype == DIGITAL_SCAN_100HZ || runtype == DIGITAL_SCAN_NOMASK) {
// Digital scan -- only storing one value per chip, no fit needed
this->mScanType = 'D';
this->initThresholdTree();
this->mFitType = NO_FIT;