-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreadWD.cpp
More file actions
1610 lines (1508 loc) · 56.1 KB
/
Copy pathreadWD.cpp
File metadata and controls
1610 lines (1508 loc) · 56.1 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
// *********************************************************************************
// * *
// * WaveDREAM Binary Data Analysis Tool *
// * *
// * *
// * Name: readWD.cpp *
// * Author: Patrick Schwendimann *
// * E-Mail: patrick.schwendimann@psi.ch *
// * Version: 0.9.4 Beta (22.06.2020) *
// * *
// * *
// * Based on the old DRS4 binary data analysis programm orignially written for *
// * the ATAR experiment by Angela Papa <angela.papa@psi.ch>, later updated by *
// * Emanuele Ripiccini, Fred Gray and Giada Rutar and an example program *
// * written by Stefan Ritt <stefan.ritt@psi.ch> for the reading of a binary *
// * file written by the DRSOsc program. *
// * *
// * Disclaimer: This code may not be fully suitable for whatever you may intend *
// * to use it for. No warranty is given. Use it always together with *
// * some common sense. *
// * Should you lack sanity or reason ... you better don't use this *
// * code. ;) *
// * *
// * Compilation requires the root packages downloadable from the CERN website *
// * *
// * https://root.cern.ch/downloading-root *
// * *
// * and the curses library (should be installed by default) *
// * *
// * *
// *********************************************************************************
#define __READ_VERSION__ "0.9.4 Beta (22.06.2020)"
// -------------------------------- Includes ---------------------------------------
// Standard libraries
#include <curses.h>
#include <fstream>
#include <iostream>
#include <cstring>
#include <stdio.h>
#include <vector>
// Root libraries
#include <TF1.h>
#include <TFile.h>
#include <TGraph.h>
#include <TH1F.h>
#include <TMath.h>
#include <TString.h>
#include <TSystem.h>
#include <TTree.h>
#include <TMatrixD.h>
#include <TVectorD.h>
// -------------------------------- Structs ----------------------------------------
/*! @struct FileHeader
@brief File header.
@details First line of binary data is the file header.
It is made by a 4-byte variable: the fourth one is the version of the DRS.
File header ||||
-|-|-|-|
'D' | 'R' | 'S' | '2' |
*/
struct FileHeader
{
char tag[3]; ///< The tag of the file header.
char version; ///< The version of the board.
};
/*! @struct EventHeader
@brief Event header.
@details Struct to store the event header. The binary file is encoded as in the next table.
Serial number starts with 1, event date/time has 16-bit values.
Event header ||||
:--:|:---:|:---:|:---:|
'E' | 'H' | 'D' | 'R' |
Event serial number||||
Year|| Mont ||
Day|| Hour ||
Minute|| Second ||
Millisecond || Range ||
*/
struct EventHeader
{
char tag[4];
unsigned int serialNumber;
unsigned short year;
unsigned short month;
unsigned short day;
unsigned short hour;
unsigned short min;
unsigned short sec;
unsigned short ms;
unsigned short rangeCenter;
};
/*! @struct IntegrationWindow
@brief Integration window.
@details Simple struct to store infos on the integration window.
*/
struct IntegrationWindow
{
int start; ///< Start of the integration window.
int stop; ///< Stop of the integration window.
};
/*! @struct Configuration
@brief Configuration struct.
@details Struct to store important variables.
*/
struct Configuration
{
Configuration();
bool firstOfRun; ///< Setted true when is the first event of the run.
///<
short debug; ///< Debug flag, passed as input `-d` or `--DEBUG` or setted from the configuration menu.
///<
short sigWF; ///< To select wether the waveform must be positive or negative sign,
///< setted from the configuration menu.
bool subtractSine; ///< Flag to subtract sine noise or not, setted from the configuration menu.
///<
float noiseFrequency; ///< The noise frequency, adjustable from the configuration menu.
///<
int runMode; ///< 0 for DRS, 1 for WDB.
///<
float intRise; ///< Number of Std.Dev. necessary to detect a signal.
///<
float intDecay; ///< Number of Tau to set the @ref IntegrationWindow stop attribute.
///<
int run; ///< Run number.
///<
unsigned int nSampleEvents; ///< Number of samples for integration window.
///<
unsigned int nSaveEvents; ///< Number of Events to save Waveforms.
///<
float cfFraction; ///<
///<
float leThreshold; ///<
///<
std::vector<unsigned int> nChannelsPerBoard; ///< Number of channels for every board.
///<
std::vector<IntegrationWindow> integrationWindows; ///< Integration windows for every board.
///<
std::vector<std::vector<float *>> timeBinWidth; ///< Width of time bin for every board.
///<
TFile *theFile; ///< The ROOT path/file where the results will be stored.
///<
};
/*! @brief @ref Configuration constructor
@details Every new @ref Configuration variable is initialized as follows:
@code{.cpp}
Configuration::Configuration()
{
debug = 0;
firstOfRun = true;
sigWF = -1;
subtractSine = false;
noiseFrequency = 50.6e+6 * TMath::TwoPi();
runMode = 1;
cfFraction = 0.2;
leThreshold = 0.05;
run = 0;
nSampleEvents = 2000;
nSaveEvents = 0;
theFile = 0;
intRise = 6;
intDecay = 3;
}
@endcode
*/
Configuration::Configuration()
{
debug = 0;
firstOfRun = true;
sigWF = -1;
subtractSine = false;
noiseFrequency = 50.6e+6 * TMath::TwoPi();
runMode = 1;
cfFraction = 0.2;
leThreshold = 0.05;
run = 0;
nSampleEvents = 2000;
nSaveEvents = 0;
theFile = 0;
intRise = 6;
intDecay = 3;
}
// ------------------------------- Global Variables --------------------------------
Configuration gCONFIG;
#define Debug \
if (gCONFIG.debug) \
std::cout << "DEBUG L" << __LINE__ << ": "
#define DEBUG \
if (gCONFIG.debug > 1) \
std::cout << "DEBUG L" << __LINE__ << ": "
#define SAMPLES_PER_WAVEFORM 1024
// -------------------------------- Declarations -----------------------------------
std::ifstream *Initialise(std::string);
int GetIntegrationBounds(std::ifstream *);
int ReadAnEvent(std::ifstream *, EventHeader &, std::vector<std::vector<float *>> &, std::vector<std::vector<unsigned short>> *);
int ReadFile(std::ifstream *);
int Config();
void PrintHelp();
void subtractSineNoise(float *, float *, float &, float &, char *);
/**
* @brief Determines mean and standard deviation of pedestal
*
* @details Determine standard deviation of the first 100 samples and the second 100 samples.
* The range with the smaller standard deviation will be used to determine the pedestal for the waveform.
*
* @param aWaveform
* @param pedestal
* @param stdv
*/
void getPedestal(float *, float &, float &);
/**
* @brief Determines mean and standard deviation of pedestal
*
* @details Determine standard deviation of the first 100 samples and the second 100 samples.
* The range with the smaller standard deviation will be used to determine the pedestal for the waveform.
*
* @param hSignal
* @param pedestal
* @param stdv
*/
void getPedestal(TH1F *, float &, float &);
float getTimeStamp(EventHeader);
// ------------------------------ Functions -----------------------------------------
void getPedestal(float *aWaveform, float &pedestal, float &stdv)
{
pedestal = 0;
stdv = 0;
float vStdv1 = TMath::StdDev(100, aWaveform);
float vStdv2 = TMath::StdDev(100, aWaveform + 100);
if (vStdv1 < vStdv2)
{
pedestal = TMath::Mean(100, aWaveform);
stdv = vStdv1;
}
else
{
pedestal = TMath::Mean(100, aWaveform + 100);
stdv = vStdv2;
}
}
void getPedestal(TH1F *hSignal, float &pedestal, float &stdv)
{
pedestal = stdv = 0;
int nBins = 100;
float meanSquares1 = 0;
float mean1 = 0;
float stdv1 = 0;
float meanSquares2 = 0;
float mean2 = 0;
float stdv2 = 0;
float x = 0;
for (int i = 0; i < nBins; ++i)
{
x = hSignal->GetBinContent(i + 1);
mean1 += x;
meanSquares1 += x * x;
x = hSignal->GetBinContent(i + nBins + 1);
mean2 += x;
meanSquares2 += x * x;
}
mean1 /= nBins;
mean2 /= nBins;
stdv1 = sqrt(meanSquares1 / nBins - mean1 * mean1);
stdv2 = sqrt(meanSquares2 / nBins - mean2 * mean2);
if (stdv1 < stdv2)
{
pedestal = mean1;
stdv = stdv1;
}
else
{
pedestal = mean2;
stdv = stdv2;
}
}
/**
* @brief Subtract sine noise from waveform
*
* @details Subtract sine noise from waveform. To be further understood.
*
* @param wfData
* @param wfTime
* @param ampl
* @param phi
* @param name
*/
void subtractSineNoise(float *wfData, float *wfTime, float &l, float &phi, char *name = 0)
{
float freq = gCONFIG.noiseFrequency;
TMatrixD M(3, 3);
TVectorD v(3);
for (int i = 0; i < 200; ++i)
{
float co = TMath::Cos(freq * wfTime[i]);
float si = TMath::Sin(freq * wfTime[i]);
M[0][0] += co * co;
M[0][1] += co * si;
M[0][2] += co;
M[1][1] += si * si;
M[1][2] += si;
M[2][2] += 1;
v[0] += co * wfData[i];
v[1] += si * wfData[i];
v[2] += wfData[i];
}
M[1][0] = M[0][1];
M[2][0] = M[0][2];
M[2][1] = M[1][2];
M.Invert();
v = M * v;
ampl = TMath::Sqrt(v[0] * v[0] + v[1] * v[1]);
phi = TMath::ATan2(v[0], v[1]);
if (name)
{
TGraph *aGraph = new TGraph(SAMPLES_PER_WAVEFORM, wfTime, wfData);
TF1 *noise = new TF1("SineNoise", "[0] * sin([1] * x + [2]) + [3]");
noise->SetNpx(1000);
noise->SetParameters(ampl, freq, phi, v[2]);
aGraph->GetListOfFunctions()->Add(noise);
aGraph->SetName(name);
aGraph->SetTitle(name);
aGraph->Write("", TObject::kOverwrite);
}
for (int i = 0; i < SAMPLES_PER_WAVEFORM; ++i)
{
wfData[i] -= ampl * TMath::Sin(freq * wfTime[i] + phi);
}
}
/**
* @brief Get the timestamp
*
* @details Get the timestamp from the event header.
*
* @param eh The event header
* @return Returns the timestamp
*/
float getTimeStamp(EventHeader eh)
{
static int lastDay = 0;
static int nDays = 0;
if (eh.serialNumber == 0)
{
lastDay = eh.day;
nDays = 0;
}
if (lastDay != eh.day)
{
lastDay = eh.day;
++nDays;
}
float timestamp = eh.ms / 1000. + eh.sec + eh.min * 60 + eh.hour * 3600 + nDays * 86400;
return timestamp;
}
/**
* @brief
*
* @param filename
* @return std::ifstream*
*/
std::ifstream *Initialise(std::string filename)
{
unsigned int nBoards = 1;
unsigned int board = 0;
float *times = 0;
char word[5];
word[4] = '\0';
std::ifstream *file = new std::ifstream;
file->open(filename, std::ios::in | std::ios::binary);
// Reset the configuration
gCONFIG.firstOfRun = true;
gCONFIG.nChannelsPerBoard.resize(0);
gCONFIG.integrationWindows.resize(0);
gCONFIG.timeBinWidth.resize(0);
// Return if unable to open the file
if (!file->is_open())
{
std::cerr << "!! Could not open file " << filename << std::endl;
delete file;
return 0;
}
FileHeader fh;
file->read((char *)&fh, sizeof(fh));
// Check file header
if (std::memcmp(fh.tag, "DRS", 3) != 0)
{
std::cerr << "!! No suitable file hedaer in file " << filename << std::endl;
file->close();
delete file;
return 0;
}
if (fh.version - '0' < 8)
{
gCONFIG.runMode = 0; // DRS
std::cout << "DRS Version " << fh.version << " : DRS Board" << std::endl;
}
else
{
gCONFIG.runMode = 1; // WDB
std::cout << "DRS Version " << fh.version << " : WDB encoding" << std::endl;
}
// Skip the time 'TIME' header
file->seekg(4, file->cur);
file->read(word, 4);
// Check board number
if (word[0] != 'B')
{
std::cerr << "!! No board header found in file " << filename << std::endl;
file->close();
delete file;
return 0;
}
std::cout << "Board 1: " << word[0] << word[1] << *(short *)(word + 2) << std::endl;
gCONFIG.nChannelsPerBoard.push_back(0);
gCONFIG.timeBinWidth.push_back({});
while (word[0] == 'C' || word[0] == 'B')
{
file->read(word, 4);
if (word[0] == 'C')
{
// Channel
gCONFIG.nChannelsPerBoard.at(board) += 1;
times = new float[SAMPLES_PER_WAVEFORM];
file->read((char *)times, sizeof(float) * SAMPLES_PER_WAVEFORM);
gCONFIG.timeBinWidth.at(board).push_back(times);
}
else if (word[0] == 'B')
{
// Board
gCONFIG.nChannelsPerBoard.push_back(0);
gCONFIG.timeBinWidth.push_back({});
++board;
++nBoards;
std::cout << "Board " << nBoards << ": " << word[0] << word[1] << *(short *)(word + 2) << std::endl;
}
}
// Check for event header
if (strcmp(word, "EHDR") != 0)
{
std::cerr << "!! No event header found: Expected EHDR, got " << word << std::endl;
Debug << "Cleaning up ... " << std::endl;
file->close();
for (board = 0; board < gCONFIG.timeBinWidth.size(); ++board)
{
for (float *arr : gCONFIG.timeBinWidth.at(board))
delete[] arr;
}
delete file;
return 0;
}
file->seekg(-4, file->cur);
return file;
}
/**
* @brief Get the Integration Bounds object
*
* @param file
* @return int
*/
int GetIntegrationBounds(std::ifstream *file)
{
int nChannelsTot = 0;
char name[32];
for (int nChannelsAtBoard : gCONFIG.nChannelsPerBoard)
{
nChannelsTot += nChannelsAtBoard;
}
// Create SampleSignal histograms
std::vector<TH1F **> hSampleSig;
for (int board = 0; board < gCONFIG.nChannelsPerBoard.size(); board++)
{
hSampleSig.push_back(new TH1F *[gCONFIG.nChannelsPerBoard.at(board)]);
for (int ch = 0; ch < gCONFIG.nChannelsPerBoard.at(board); ++ch)
{
sprintf(name, "hSampleSigB%03dC%03d", board + 1, ch);
hSampleSig.at(board)[ch] = new TH1F(name, name, SAMPLES_PER_WAVEFORM, -0.5, SAMPLES_PER_WAVEFORM - 0.5);
// Attribute the histos with the root output file. Memory will be freed when closing the file
hSampleSig.at(board)[ch]->SetDirectory(gCONFIG.theFile);
Debug << "Created histogram " << name << std::endl;
}
}
// Read some data and fill the histos
EventHeader eh;
std::vector<std::vector<float *>> wfData;
for (int board = 0; board < gCONFIG.nChannelsPerBoard.size(); board++)
{
wfData.push_back({});
for (int ch = 0; ch < gCONFIG.nChannelsPerBoard.at(board); ++ch)
wfData.at(board).push_back(new float[SAMPLES_PER_WAVEFORM]);
}
float pedestal = 0;
float pedStdv = 0;
unsigned int nEvents = 0;
int retVal = 0;
int curPos = file->tellg();
while (nEvents < gCONFIG.nSampleEvents && !file->eof())
{
retVal = ReadAnEvent(file, eh, wfData, 0);
if (retVal)
break;
for (int board = 0; board < gCONFIG.nChannelsPerBoard.size(); board++)
{
for (int ch = 0; ch < gCONFIG.nChannelsPerBoard.at(board); ++ch)
{
getPedestal(wfData.at(board).at(ch), pedestal, pedStdv);
for (int i = 0; i < SAMPLES_PER_WAVEFORM; ++i)
{
hSampleSig.at(board)[ch]->Fill(i, wfData.at(board).at(ch)[i] - pedestal);
}
}
}
}
if (retVal < 2)
{
float peak, stdv, tau;
int peakBin;
TH1F *hSample = 0;
TF1 *gaus = new TF1("gaus", "gaus(0)");
TF1 *decay = new TF1("decay", "[0] * exp( -(x - [1]) / [2])");
TF1 *intWin = new TF1("intWindow", "[0]");
intWin->SetLineColor(419);
intWin->SetLineWidth(3);
IntegrationWindow iw;
std::cout << "Integration Windows:\nCh\tstart\tstop\n";
// Fit the samples if reasonable
for (int board = 0; board < gCONFIG.nChannelsPerBoard.size(); ++board)
{
for (int ch = 0; ch < gCONFIG.nChannelsPerBoard.at(board); ++ch)
{
hSample = hSampleSig.at(board)[ch];
hSample->GetXaxis()->SetRange(2, 0.9 * SAMPLES_PER_WAVEFORM);
peak = hSample->GetMinimum();
peakBin = hSample->GetMinimumBin();
hSample->GetXaxis()->SetRange(1, SAMPLES_PER_WAVEFORM);
getPedestal(hSample, pedestal, pedStdv);
Debug << "peak : " << peak << " bin: " << peakBin << std::endl;
if (peak < pedestal - 5 * pedStdv)
{
// There is at least a five sigma excess
// This channel probably collected a waveform
decay->FixParameter(0, peak);
decay->FixParameter(1, peakBin);
decay->SetParameter(2, 10);
decay->SetRange(peakBin, 1000);
hSample->Fit(decay, "RQ0");
hSample->GetFunction("decay")->ResetBit(TF1::kNotDraw);
gaus->FixParameter(0, peak);
gaus->FixParameter(1, peakBin);
gaus->SetParameter(2, 10);
gaus->SetRange(1, peakBin);
hSample->Fit(gaus, "RQ0+");
hSample->GetFunction("gaus")->ResetBit(TF1::kNotDraw);
stdv = fabs(gaus->GetParameter(2));
tau = fabs(decay->GetParameter(2));
iw.start = peakBin - gCONFIG.intRise * stdv;
iw.stop = peakBin + gCONFIG.intDecay * tau;
if (iw.start < 0)
iw.start = 0;
if (iw.stop > SAMPLES_PER_WAVEFORM - 1)
iw.stop = SAMPLES_PER_WAVEFORM - 1;
}
else
{
// There is probably no signal - integrate over the whole time window
iw.start = 0;
iw.stop = SAMPLES_PER_WAVEFORM - 1;
}
intWin->SetRange(iw.start, iw.stop);
intWin->FixParameter(0, pedestal);
if (pedestal != 0)
{
hSample->Fit(intWin, "RQ0+");
hSample->GetFunction("intWindow")->ResetBit(TF1::kNotDraw);
}
gCONFIG.integrationWindows.push_back(iw);
std::printf("%d\t%d\t%d\n", ch, iw.start, iw.stop);
}
}
// Deleting the functions
gaus->Delete();
decay->Delete();
intWin->Delete();
}
// Clean up
for (std::vector<float *> ch : wfData)
{
for (float *f : ch)
delete[] f;
}
for (int board = 0; board < gCONFIG.nChannelsPerBoard.size(); ++board)
{
for (int ch = 0; ch < gCONFIG.nChannelsPerBoard.at(board); ++ch)
{
hSampleSig.at(board)[ch]->Write("", TObject::kOverwrite);
}
delete[] hSampleSig.at(board);
}
// Return 1 if eof was reached, 0 when nSampleEvents were read
file->seekg(curPos);
return (nEvents < gCONFIG.nSampleEvents);
}
/**
* @brief Reads an event
*
* @details Reads an event in parallel from any channel available.
*
* @param file Input file, opened with Initialise() and the current position at the beginning of the EHDR
* @param eh Event header at which the event will be read
* @param wfData Waveform data at which the waveform data will be read
* @param tCell Trigger cell
* @return 0 on success, 1 for EOF, 2 otherwise
*/
int ReadAnEvent(std::ifstream *file, EventHeader &eh, std::vector<std::vector<float *>> &wfData, std::vector<std::vector<unsigned short>> *tCell)
{
// Input: file - std::ifstream opened with Initialise() and the current position at the beginning of the EHDR.
// eh - to this variable the event header will be read
// wfData - to this variable the waveform data will be read. Memory already properly alocated!
// tCell - if valid address, the trigger cells will be stored to this address.
// Return: 0 on success, 1 for eof, 2 otherwise
// the std::ifstream file will be at the very end of the event - next thing read should be the new EHDR.
// Further: The details of the read data depends on gCONFIG.nChannelsPerBoard.
char word[5]; // A default word to read from a file
word[4] = '\0'; // 4 bytes to read + 1 \0 character to terminate for printing purposes
unsigned short voltages[SAMPLES_PER_WAVEFORM]; // Voltages for a single channel to read from the file.
unsigned short index = 0; // Current channel number;
// Get the last position in the file
static long lastPos = 0;
static long eventSize = 0;
if (gCONFIG.firstOfRun || not lastPos || not eventSize)
{
long curPos = file->tellg();
file->seekg(0, file->end);
lastPos = file->tellg();
file->seekg(curPos);
gCONFIG.firstOfRun = false;
}
// Read event header first
file->read((char *)&eh, sizeof(eh));
if (std::memcmp(eh.tag, "EHDR", 4) != 0)
{
std::cerr << "!! No valid event header found. Found " << eh.tag << " instead" << std::endl;
return 2;
}
DEBUG << "Reading event " << eh.serialNumber << std::endl;
// Looping over all channels and all boards
int totCh = 0;
for (unsigned int board = 0; board < gCONFIG.nChannelsPerBoard.size(); ++board)
{
file->read(word, 4);
if (std::memcmp(word, "B#", 2) != 0)
{
std::cerr << "No valid board header found. Found " << word << " instead" << std::endl;
return 2;
}
DEBUG << " -found data for board " << *(short *)(word + 2) << std::endl;
if (gCONFIG.runMode == 0)
{
// DRS encoding
// Read trigger cell
file->read(word, 4);
if (std::memcmp(word, "T#", 2) != 0)
{
std::cerr << "No valid trigger cell found. Found " << word << " instead" << std::endl;
return 2;
}
DEBUG << "Trigger cell: " << *(unsigned short *)(word + 2) << std::endl;
if (tCell)
{
for (unsigned int i = 0; i < tCell->at(board).size(); ++i)
tCell->at(board).at(i) = *(unsigned short *)(word + 2);
}
}
file->read(word, 4);
while (word[0] == 'C')
{
++totCh;
char iCh[10];
std::memcpy(iCh, word + 1, 3);
iCh[3] = 0;
index = std::stoi(iCh);
DEBUG << "Found data for channel " << word << std::endl;
// Read scaler - and ignore it for now
file->read(word, 4);
if (gCONFIG.runMode == 1)
{
// Read trigger cell
file->read(word, 4);
if (std::memcmp(word, "T#", 2) != 0)
{
std::cerr << "No valid trigger cell found. Found " << word << " instead" << std::endl;
return 2;
}
DEBUG << "Trigger cell: " << *(unsigned short *)(word + 2) << std::endl;
if (tCell)
tCell->at(board).at(index) = *(unsigned short *)(word + 2);
}
// Read voltages from file
int curPos = file->tellg();
file->read((char *)voltages, sizeof(voltages));
std::cout << index << std::endl;
for (int bin = 0; bin < SAMPLES_PER_WAVEFORM; ++bin)
{
wfData.at(board).at(index)[bin] = (voltages[bin] / 65536. + eh.rangeCenter / 1000. - 0.5);
}
if (!file->eof())
{
file->read(word, 4);
}
}
}
for (int board = 0; board < gCONFIG.nChannelsPerBoard.size(); ++board)
{
for (int ch = 0; ch < gCONFIG.nChannelsPerBoard.at(board); ++ch)
{
if (wfData.at(board).at(ch)[0] == 0)
{
for (int bin = 0; bin < SAMPLES_PER_WAVEFORM; ++bin)
wfData.at(board).at(ch)[bin] = -1.;
}
}
}
// if (std::memcmp(word, "EHDR", 4) != 0)
// {
// std::cerr << "No valid channel header or event header found. Found " << word << " instead" << std::endl;
// return 2;
// }
eventSize = 0;
if (gCONFIG.runMode == 1)
{
// WDB event encoding
eventSize += sizeof(EventHeader); // 1 Event header
eventSize += 4 * gCONFIG.nChannelsPerBoard.size(); // 4 byte board header per board
// 4 Byte channel header, 4 byte scaler, 4 byte Trigger header + data
eventSize += (12 + sizeof(voltages)) * totCh;
}
else
{
// DRS event encoding
eventSize += sizeof(EventHeader); // 1 Event header
eventSize += 8 * gCONFIG.nChannelsPerBoard.size(); // 4 byte board header per board + trigger header
// 4 Byte channel header, 4 byte scaler + data
eventSize += (8 + sizeof(voltages)) * totCh;
}
DEBUG << "File status: " << file->tellg() << "/" << lastPos << " Event Size: " << eventSize << std::endl;
// Assert that the file is not at its end
if (lastPos - file->tellg() < eventSize)
{
DEBUG << "File is at its end: " << file->tellg() << "/" << lastPos << " Event Size: " << eventSize << std::endl;
return 1;
}
file->seekg(-4, file->cur);
return 0;
}
/**
* @brief Read the whole file
*
* @details Read the whole .dat file and write the values to a tree. The tree gets saved to
* the file gCONFIG.theFile.
*
* @param file Opened .dat file. The current position is at the first event header.
* @return 0 on success, 1 otherwise
*/
int ReadFile(std::ifstream *file)
{
int retVal = 0; ///< The value to be returned
// Initialise the tree
// 1. Number of channels and leaflist description
int nChannelsTot = 0;
std::string leaflistDescription = "ch0";
for (int nChannels : gCONFIG.nChannelsPerBoard)
{
nChannelsTot += nChannels;
}
for (int ch = 1; ch < nChannelsTot; ++ch)
{
leaflistDescription += ":ch";
leaflistDescription += std::to_string(ch);
}
Debug << leaflistDescription << std::endl;
// 2. Variables to fill the tree from
int fRun = gCONFIG.run;
int fEvent = 0;
float fTimestamp = 0;
float *fTime = new float[nChannelsTot];
float *fTimeLE = new float[nChannelsTot];
float *fAmplitude = new float[nChannelsTot];
float *fArea = new float[nChannelsTot];
float *fArea2 = new float[nChannelsTot];
float *fPed = new float[nChannelsTot];
float *fStdv = new float[nChannelsTot];
float *fThreshold = new float[nChannelsTot];
float *fStdvRaw = new float[nChannelsTot];
float *fSineAmplitude = new float[nChannelsTot];
float *fSinePhase = new float[nChannelsTot];
// 3. TTree itself
TTree *theTree = new TTree("T", "WaveDREAM Tree");
theTree->SetDirectory(gCONFIG.theFile);
theTree->Branch("runnumber", &fRun);
theTree->Branch("event", &fEvent);
theTree->Branch("timestamp", &fTimestamp);
theTree->Branch("time", fTime, leaflistDescription.c_str());
theTree->Branch("timeLE", fTimeLE, leaflistDescription.c_str());
theTree->Branch("amplitude", fAmplitude, leaflistDescription.c_str());
theTree->Branch("area", fArea, leaflistDescription.c_str());
theTree->Branch("area2", fArea2, leaflistDescription.c_str());
theTree->Branch("ped", fPed, leaflistDescription.c_str());
theTree->Branch("Stdv", fStdv, leaflistDescription.c_str());
theTree->Branch("Threshold", fThreshold, leaflistDescription.c_str());
if (gCONFIG.subtractSine)
{
theTree->Branch("StdvRaw", fStdvRaw, leaflistDescription.c_str());
theTree->Branch("SineAmplitude", fSineAmplitude, leaflistDescription.c_str());
theTree->Branch("SinePhase", fSinePhase, leaflistDescription.c_str());
}
Debug << "TTree initialised " << std::endl;
if (gCONFIG.debug)
theTree->Print();
// Start the mainloop
Debug << "Mainloop over the file started " << std::endl;
EventHeader eh;
std::vector<std::vector<float *>> wfData;
std::vector<std::vector<float *>> wfTime;
std::vector<std::vector<unsigned short>> tCell;
for (int board = 0; board < gCONFIG.nChannelsPerBoard.size(); board++)
{
wfData.push_back({});
wfTime.push_back({});
tCell.push_back({});
for (int ch = 0; ch < gCONFIG.nChannelsPerBoard.at(board); ++ch)
{
wfData.at(board).push_back(new float[SAMPLES_PER_WAVEFORM]);
wfTime.at(board).push_back(new float[SAMPLES_PER_WAVEFORM]);
tCell.at(board).push_back(0);
}
}
float t1, t2, dt;
int index = 0;
// Variables to be later filled into the tree
float timeCF, timeLE, ampl, area, area2, ped, stdv, stdvRaw, sinAmpl, phi, thr;
bool isSignal = false;
int minBin = 0;
float firstMin = 0;
while (not file->eof())
{
retVal = ReadAnEvent(file, eh, wfData, &tCell);
if (retVal)
break;
if (eh.serialNumber % 100 == 0)
{
std::cout << "Processing Event " << eh.serialNumber << std::endl;
};
// Calculate times for each channel
for (int board = 0; board < gCONFIG.nChannelsPerBoard.size(); ++board)
{
for (int ch = 0; ch < gCONFIG.nChannelsPerBoard.at(board); ++ch)
{
int bin = tCell.at(board).at(ch);
double time = 0;
for (int i = 0; i < SAMPLES_PER_WAVEFORM; ++i)
{
wfTime.at(board).at(ch)[i] = time;
time += gCONFIG.timeBinWidth.at(board).at(ch)[bin];
++bin;
bin %= 1024;
}
}
}
// Align cell #0 of all channels
index = 0;
for (int board = 0; board < gCONFIG.nChannelsPerBoard.size(); ++board)
{
t1 = wfTime.at(board).at(index)[(1024 - tCell.at(board)[index]) % 1024];
++index;
for (int ch = 1; ch < gCONFIG.nChannelsPerBoard.at(board); ++ch)
{
t2 = wfTime.at(board).at(index)[(1024 - tCell.at(board)[index]) % 1024];
dt = t1 - t2;
for (int i = 0; i < SAMPLES_PER_WAVEFORM; ++i)
{
wfTime.at(board).at(index)[i] += dt;
}
++index;
}
}
// Analysis of individual channels
int nCh = 0;
for (int board = 0; board < gCONFIG.nChannelsPerBoard.size(); ++board)
{
for (int ch = 0; ch < gCONFIG.nChannelsPerBoard.at(board); ++ch)
{
float *aWF = wfData.at(board).at(ch);
float *aWFT = wfTime.at(board).at(ch);
// Flip waveform if needed -> want a negative one
if (gCONFIG.sigWF == 1)
{
for (int i = 0; i < SAMPLES_PER_WAVEFORM; ++i)
aWF[i] *= -1;
Debug << "Positive Waveform - flipping" << std::endl;
}
// Subtract sine noise if activated
if (gCONFIG.subtractSine && abs(aWF[0]) != 1.)
{
getPedestal(aWF, ped, stdvRaw);
if (eh.serialNumber < gCONFIG.nSaveEvents)
{
char name[32];
sprintf(name, "event%03d_ch%03d_raw", eh.serialNumber, ch);
subtractSineNoise(aWF, aWFT, sinAmpl, phi, name);
}
else
{
subtractSineNoise(aWF, aWFT, sinAmpl, phi);
}
}
// Get the pedestal
getPedestal(aWF, ped, stdv);
// Check for a signal waveform - aka 5 sigma excess
// May needs a somewhat less restrictive cut
isSignal = false;
IntegrationWindow iw = gCONFIG.integrationWindows.at(nCh);
for (int i = iw.start; i < iw.stop && not isSignal; ++i)
{
if ((ped - aWF[i]) > 5 * stdv)
isSignal = true;
}