Compare commits

...

108 Commits

Author SHA1 Message Date
Ryan Tang 96818dae99
Create LICENSE 2024-12-07 14:29:35 -05:00
Ryan Tang 770d2c5af4 I tested with QDC AMC version 135.17, the Overthreshold is working. 2024-11-21 18:40:07 -05:00
Ryan Tang d3f97358e2 QDC, Add the OverThresholdWidth setting, but only for ROC > 4.15 and AMC > 135.15 2024-11-21 18:21:32 -05:00
Ryan Tang c1f223532c added a button on the channel setting to set default channel settings for Si-detector 2024-11-01 17:03:10 -04:00
Ryan Tang 9bdd6b77eb seperate out ProgramChannel from ProgramBoard in Digitizer Class 2024-11-01 16:42:31 -04:00
Ryan Tang 81b2fba623 Rename trigger : Independent --> Normal, Trig Valid, from Both From Mather Board to Both from TRG_VAL; More GUI bugs fix for trigger related settings 2024-10-31 18:03:12 -04:00
Ryan Tang 2be9d34320 UI bugs fix 2024-10-30 18:48:00 -04:00
Ryan Tang 4eca8eb09a fix a bug for PHA 2024-10-30 15:42:45 -04:00
Ryan Tang 1562d9cab2 add QDC group copy 2024-10-28 15:41:54 -04:00
Ryan Tang e856a1cddf fix copy channels 2024-10-28 15:36:40 -04:00
Ryan Tang c7feaec471 small improvement, Event/Agg for PHA/PSD < 512 2024-10-28 15:12:26 -04:00
Ryan Tang 8b7d93a9fe When open digi setting or Scope, update settings from memory 2024-10-28 13:24:38 -04:00
Ryan Tang 4ab72dc43d fix all code with parallel thread 2024-10-22 16:38:01 -04:00
Ryan Tang fe6bdb82ff simplify code for multi thread 2024-10-22 13:56:26 -04:00
Ryan Tang b8011bc834 [Major] True parallel thread for filling histogram 2024-10-22 12:56:26 -04:00
Ryan Tang 0d379fec92 use AbsDataIndex in MultiBuilder 2024-10-21 19:53:42 -04:00
Ryan Tang ae0e0f2c7b add ClassData::GetAbsDataIndex() 2024-10-21 19:47:02 -04:00
Ryan Tang 39f479534e simplify SingleSpectra.cpp 2024-10-21 19:25:30 -04:00
Ryan Tang 804fa07c9c add QCoreApplication::processEvent() to solve the GUI lagging 2024-10-21 19:11:44 -04:00
Ryan Tang 4e111085c0 in ClassDigitizer, get data can use totalIndex, which will % dataSize. simplify HistFilling. Qthread will block mainGUI ? 2024-10-21 19:09:44 -04:00
Ryan Tang ae567c0714 improve scope for QDC and PSD, add subChannelMask in Scope 2024-10-21 15:11:33 -04:00
Ryan Tang 9367670a53 bug fix of Scope, only-1-channel for QDC 2024-10-18 17:54:43 -04:00
Ryan Tang d67dc8d3ed add elog port number 2024-10-18 16:30:21 -04:00
Ryan Tang 2e9a64ccfd Histogram2D, nan value is transperant 2024-10-16 19:11:15 -04:00
Ryan Tang 921580a6c6 small bug fix for Filling Historgam when trigge rate > 10k 2024-10-16 18:32:20 -04:00
Ryan Tang 3f007cebbd comment out more 2024-10-16 18:18:50 -04:00
Ryan Tang c2e76c75ae comment out printf 2024-10-16 18:00:07 -04:00
Ryan Tang 88823af2c6 change the Decimation for QDC to be average of 2^n 2024-10-16 17:57:12 -04:00
Ryan Tang 84b89cb36a change the SingleSpectra::FillHistogram() Algorithm 2024-10-16 16:56:59 -04:00
Ryan Tang f8b9abc70d remove any UpdatePlot in SingleSpectra::FillHistogram 2024-10-15 17:27:16 -04:00
Ryan Tang 83fbea2743 bug fix on Histogram2D 2024-10-15 17:23:43 -04:00
Ryan Tang fa3e015e3e Created an artifical Register 0x8044 for SWDecimation. Simplify a lot of things 2024-10-14 18:33:18 -04:00
Ryan Tang 256390ffaf added SW Decimation on the Digi setting panle for QDC. this setting is not saved in setting file 2024-10-14 17:47:11 -04:00
Ryan Tang 2f55f6ecb5 add software waveform decimation to reduce raw data file size 2024-10-14 16:51:02 -04:00
Ryan Tang 25d074a393 update the master branch from 0ee20bc 2024-09-30 18:38:48 -04:00
Ryan Tang d8c6fa2246 add FSUDAQ bash script, to pipe the stout to a log file 2024-09-09 14:38:08 -04:00
Ryan Tang d738971435 add maskText to mask password 2024-09-09 14:22:21 -04:00
Ryan Tang b3692705ab add core dump when segfault 2024-09-09 14:00:43 -04:00
Ryan Tang 968259787b when open digitizer, always set no trace recording 2024-09-06 18:16:18 -04:00
carina@hades 3b3a22382b [Major] Scalar cannot be put in Thread, becuase it update QLineEdit of the MainThread and it is not thread-safe 2024-09-04 17:50:59 -04:00
Ryan Tang dfdc5c4700 fixed a UI issue for PSD channel, the SetUpComBoBoxBit cannot span col 2024-09-04 16:39:19 -04:00
Ryan Tang 13b2a3d63d Set PSD default is fine time. fix UI bug for PSD 2024-09-04 16:26:21 -04:00
carina@hades 8baa37142c add some debug code in EventBuilder and fsuReader.h, ReadBatch can switch off trace 2024-09-04 03:09:08 -04:00
Ryan Tang 06592c6aca ClassData.h, fix PSD decoder verbose display 2024-09-03 15:55:58 -04:00
Ryan Tang 540f967d70 ClassData.h, fine_time = -1 as default 2024-09-03 15:49:15 -04:00
Ryan Tang e79f93e9ab add Locale 2024-08-30 12:27:24 -04:00
Ryan Tang 11ae70db18 remove scope Qtimer for scalar, use the Scope::TellACQOnOff to start/stop work for scalar, singleHostogram, and onlineAnalyzer 2024-08-29 17:15:36 -04:00
Ryan Tang c2265f3cc6 remove TimingThread, Scope::UpdateScope() in Qthread via a worker. ScalarUpdateTimeinMiliSec in macro.h 2024-08-29 16:49:52 -04:00
Ryan Tang 2abdc83549 added analyzer/README.md, move the isWorking from the custom analyzer to Analyzer, so user don't need to worry 2024-08-29 15:47:07 -04:00
Ryan Tang b3ace2cc84 [MAJOR] Analayzer::UpdateHistograms moved to a worker that in a thread, only tested with CoincidentAnalyzer, need to change others 2024-08-29 14:45:11 -04:00
Ryan Tang a5914f8ff8 restructure the workers 2024-08-28 17:58:12 -04:00
Ryan Tang a08297d5cc Move updateScalar into a ScalarWorker, which live in a new Thread 2024-08-28 17:22:41 -04:00
Ryan Tang fbd98067da remove some printf, remove Rebin button in SingleSpatra class 2024-08-28 16:53:25 -04:00
Ryan Tang 0a751eaab1 [Major] remove histogram timing thread, make a new worker, move to a thread to fill histograms 2024-08-28 16:45:23 -04:00
Ryan Tang 55210083fc in Aux/test.cpp, compare CAEN_DGTZ_GetDPPEvents for decode data 2024-08-28 14:17:39 -04:00
Ryan Tang 76f8f22204 default PSD program set baseline to be 16 samples 2024-08-27 18:13:01 -04:00
Ryan Tang ffb009e6da bug fix on Data::CopyBuffer() 2024-08-27 12:48:00 -04:00
Ryan Tang a32a1e0e71 bug fix, remove trailling space for influx inputs 2024-08-26 15:25:19 -04:00
Ryan Tang dbfb9f96bf add SetDataBase in Analysis, so all analyzsis class can use 2024-08-26 13:59:04 -04:00
Ryan Tang ef8dca5430 remove printf in NeutronGamma::UpdateHistograms 2024-08-23 18:39:21 -04:00
Ryan Tang f3fea48bf6 bug fix on filling Historgram 1D 2024-08-23 18:26:56 -04:00
Ryan Tang 823adf67eb disable digitizer panel button when ACQ started 2024-08-23 16:24:17 -04:00
Ryan Tang bf989d2c72 allow open digitizer panel when ACQ started 2024-08-22 15:56:19 -04:00
Ryan Tang fa2b1012dd Digiti Panel is not disable when ACQ started, but the value does not change 2024-08-22 13:03:43 -04:00
Ryan Tang 1cb60d1aa4 bugfix NeutronGamma; if scalarThred running + Analyzer created -> start updateHistograms thread 2024-08-22 12:42:08 -04:00
Ryan Tang 82de3763a9 delete the timing thread in Analyzer 2024-08-21 14:50:55 -04:00
Ryan Tang e780345557 edit README.md 2024-08-21 13:40:11 -04:00
Ryan Tang 6a9f254289 DigiSetting PSD bug fix, add NeutronGamma analyzer 2024-08-20 14:59:22 -04:00
Ryan Tang 5ebff17f89 Histogram1D: ymax only update when line is visible 2024-08-20 12:31:36 -04:00
Ryan Tang 6faeaf7c9b add Toggle line display on histogram 1D 2024-08-20 12:22:26 -04:00
Ryan Tang a58ddbc6d4 bugs fix for online histograms 2024-08-20 11:20:12 -04:00
Ryan Tang 0895ad57ed SingleHistogram add energy Long for PSD, add SplotPolePlotter_MT.C 2024-08-19 18:53:59 -04:00
Ryan Tang e13db06ed3 remove unneccesary mutex lock aand unlock for read only operations 2024-08-19 12:27:51 -04:00
Ryan Tang 36621dcf31 update Aux/README.md 2024-08-14 13:52:36 -04:00
Ryan Tang f65a6f9ef5 EventBuilder only output root file, and FSU2CAEN output CoMPASS BIN. the CoMPASS BIN can be converted to root using other repository 2024-08-14 13:46:52 -04:00
Ryan Tang 9af7ff721c after SPS test 2024-08-13 12:45:24 -04:00
Ryan Tang 3f24baa0aa small tune for MultiBuilder.cpp 2024-08-06 17:28:25 -04:00
Ryan Tang 6f0cdb22b6 update FSUDAQ_Qt6.pro for the MUSICAnalyzer 2024-08-06 16:05:21 -04:00
Ryan Tang 94bae83a65 Merge branch 'master' of https://fsunuc.physics.fsu.edu/git/rtang/FSUDAQ_Qt6 2024-08-06 16:01:05 -04:00
Ryan Tang 8c9f8df08e edited Aux/SplitPolePlotter.C 2024-08-06 16:00:33 -04:00
MUSIC 002a10b4e0 bug fix on MUSICAnalyzer.h 2024-08-01 16:03:50 -05:00
MUSIC 478d1cdf38 add MUSIC Analyr. Online evt buidr fail... 2024-07-30 11:56:10 -05:00
MUSIC f7a7dff2a3 screen too small fix again 2024-07-26 14:48:20 -05:00
Calem@RAISOR 779c4a87c9 resize window when screen too small 2024-07-26 14:21:16 -05:00
Ryan Tang 3fc682f918 replace splitpole.C/h to SplitPolePlotter.C, to TreeReader 2024-07-19 15:00:29 -04:00
Ryan Tang 00ddf3dcf5 Small change of EventBuilder to support TTreeReader. add SpliitPolePlotter.C 2024-07-17 18:41:47 -04:00
splitPoleDAQ 064c99256b add spltpole.C/h in Aux 2024-07-17 16:02:36 -04:00
Ryan Tang c4263ab06c fix CAEN format. the header only at the beginning of the binary file 2024-07-17 15:30:27 -04:00
Ryan Tang 84bb439ff3 Event Builder can output CAEN binary 2024-07-17 14:53:49 -04:00
Ryan Tang cc296f6e94 tested Coincident Analyzer for 20 kHz/channel, backward event builder. added save/load settings for that too 2024-06-28 15:08:58 -04:00
Ryan Tang dde7e39685 added control for using influx and elog 2024-06-27 17:27:28 -04:00
Ryan Tang c8e032390a Histogram2D.h add save/load graphic cuts into/from txt file 2024-06-27 16:51:31 -04:00
Ryan Tang 839b3d2a58 fix CoincidentAnalyzer.h 2024-06-26 17:35:09 -04:00
Ryan Tang 0371f0c560 comment out GDB debug in *.pro 2024-06-26 16:42:37 -04:00
Ryan Tang 5f2a7f067d change MainWindow Class to FSUDAQ Class. fix bug on histThread, fix bug on CoincidentAnalyzer.h 2024-06-26 16:40:40 -04:00
Ryan Tang 6fcebf0c06 Split-Pole analyzer, disable reaction when run analyzer 2024-06-20 13:50:44 -04:00
Ryan Tang 9ea67c4554 remove user input for batch size for EventBuilder and FSU2CAEN 2024-06-19 16:59:16 -04:00
Ryan Tang b9d1a76b7e fsuReader, Scanning fsu file will estimate the best batch size 2024-06-19 16:55:38 -04:00
Ryan Tang 0e8c92a266 when no event build, the suffix is 'single' instead of '-1' 2024-06-18 16:47:54 -04:00
Ryan Tang 02305314ba EventBuilder, trace stored as fixed size array of array 2024-06-18 16:33:23 -04:00
Ryan Tang 1b3c1733ce FSU2CAEN add the energy short 2024-06-18 14:37:23 -04:00
Ryan Tang bbe9ef7990 ClassData, fine timestamp in ps. added flags and trace for FSU2CAEN 2024-06-18 14:15:46 -04:00
Ryan Tang ae6b133138 added FSU2CAEN.cpp, this is a program to timesort the fsu files and output to CoMPASS binary format 2024-06-18 13:45:08 -04:00
Ryan Tang d0133cc864 bugs fix on SingleSpectrum 2D historgram not loading saved setting 2024-06-17 17:44:31 -04:00
Ryan Tang 106fe3f155 change some names in MultiBuilder.h, add setting for event time window in SPlitpotle analyszer 2024-06-13 16:12:29 -04:00
Ryan Tang e9e5ae3023 ClassData::ClearData reset the outFileIndex = 0 2024-06-13 14:55:51 -04:00
Ryan Tang a9b98c36f3 snapshot 2024-06-11 16:15:50 -04:00
Ryan Tang dcb3d73776 add prefix in RunTimeStamp.dat 2024-06-10 16:22:01 -04:00
50 changed files with 5650 additions and 2013 deletions

12
.gitignore vendored
View File

@ -1,6 +1,7 @@
*.o
*.fsu
*.root
core.FSUDAQ*
FSUDAQ_Qt6
test
@ -20,16 +21,21 @@ DAQLock.dat
DumpFSU2ROOT
SettingsExplorer
AggSeparator
FSU2CAEN
Bin2Root
data
splitpole.C
splitpole.h
Data
raw_binary
log
*.d
*.pcm
*.txt
*.tar
*.tar.gz
*.BIN
*~
*.autosave

58
.vscode/settings.json vendored
View File

@ -82,39 +82,36 @@
}
],
"files.associations": {
"mainWindow.C": "cpp",
"Scope.C": "cpp",
"new": "cpp",
"allocator": "cpp",
"array": "cpp",
"istream": "cpp",
"ostream": "cpp",
"sstream": "cpp",
"limits": "cpp",
"atomic": "cpp",
"bit": "cpp",
"*.tcc": "cpp",
"bitset": "cpp",
"*.C": "cpp",
"*.pro": "makefile",
"regex": "cpp",
"cctype": "cpp",
"chrono": "cpp",
"clocale": "cpp",
"cmath": "cpp",
"codecvt": "cpp",
"compare": "cpp",
"concepts": "cpp",
"condition_variable": "cpp",
"cstdarg": "cpp",
"cstddef": "cpp",
"cstdint": "cpp",
"cstdio": "cpp",
"cstdlib": "cpp",
"cstring": "cpp",
"ctime": "cpp",
"cwchar": "cpp",
"cwctype": "cpp",
"array": "cpp",
"atomic": "cpp",
"bit": "cpp",
"*.tcc": "cpp",
"bitset": "cpp",
"charconv": "cpp",
"chrono": "cpp",
"codecvt": "cpp",
"compare": "cpp",
"concepts": "cpp",
"condition_variable": "cpp",
"cstdint": "cpp",
"deque": "cpp",
"list": "cpp",
"map": "cpp",
"set": "cpp",
"string": "cpp",
"unordered_map": "cpp",
"unordered_set": "cpp",
@ -129,38 +126,35 @@
"optional": "cpp",
"random": "cpp",
"ratio": "cpp",
"source_location": "cpp",
"string_view": "cpp",
"system_error": "cpp",
"tuple": "cpp",
"type_traits": "cpp",
"utility": "cpp",
"format": "cpp",
"fstream": "cpp",
"future": "cpp",
"initializer_list": "cpp",
"iomanip": "cpp",
"iosfwd": "cpp",
"iostream": "cpp",
"istream": "cpp",
"limits": "cpp",
"mutex": "cpp",
"new": "cpp",
"numbers": "cpp",
"ostream": "cpp",
"semaphore": "cpp",
"shared_mutex": "cpp",
"span": "cpp",
"sstream": "cpp",
"stdexcept": "cpp",
"stop_token": "cpp",
"streambuf": "cpp",
"thread": "cpp",
"cinttypes": "cpp",
"typeinfo": "cpp",
"variant": "cpp",
"qmainwindow": "cpp",
"qchartview": "cpp",
"qthread": "cpp",
"qrandomgenerator": "cpp",
"source_location": "cpp",
"splitpole.C": "cpp",
"forward_list": "cpp",
"fstream": "cpp",
"Analyzer.C": "cpp",
"process_Run.C": "cpp",
"EncoreAnalyzer.C": "cpp",
"qfiledialog": "cpp"
"variant": "cpp"
}
}

View File

@ -7,9 +7,10 @@
#include "TFile.h"
#include "TTree.h"
#include "TMacro.h"
#include "TMath.h"
#define MAX_MULTI 2000
#define MAX_TRACE_LENGTH 2000
#define MAX_MULTI 100
struct FileInfo{
@ -19,6 +20,9 @@ struct FileInfo{
};
#define NMINARG 4
#define debug 0
//^#############################################################
//^#############################################################
int main(int argc, char **argv) {
@ -26,16 +30,15 @@ int main(int argc, char **argv) {
printf("=========================================\n");
printf("=== *.fsu Events Builder ===\n");
printf("=========================================\n");
if (argc < 6) {
if (argc < NMINARG) {
printf("Incorrect number of arguments:\n");
printf("%s [timeWindow] [withTrace] [verbose] [batchSize] [inFile1] [inFile2] .... \n", argv[0]);
printf("%s [timeWindow] [withTrace] [inFile1] [inFile2] .... \n", argv[0]);
printf(" timeWindow : in ns, -1 = no event building \n");
printf(" withTrace : 0 for no trace, 1 for trace \n");
printf(" verbose : > 0 for debug \n");
printf(" batchSize : the size of hit in a batch \n");
printf(" Output file name is contructed from inFile1 \n");
printf("\n");
printf(" Example: %s 0 0 0 10000 '\\ls -1 *001*.fsu'\n", argv[0]);
printf(" Example: %s -1 0 '\\ls -1 *001*.fsu' (no event build, no trace, no verbose)\n", argv[0]);
printf(" %s 100 0 '\\ls -1 *001*.fsu' (event build with 100 ns, no trace, no verbose)\n", argv[0]);
printf("\n\n");
return 1;
@ -46,11 +49,12 @@ int main(int argc, char **argv) {
///============= read input
long timeWindow = atoi(argv[1]);
bool traceOn = atoi(argv[2]);
unsigned int debug = atoi(argv[3]);
unsigned int batchSize = atoi(argv[4]);
int nFile = argc - 5;
// unsigned int debug = atoi(argv[3]);
// unsigned short format = atoi(argv[3]);
unsigned int batchSize = 2* DEFAULT_HALFBUFFERSIZE;
int nFile = argc - NMINARG + 1;
TString inFileName[nFile];
for( int i = 0 ; i < nFile ; i++){ inFileName[i] = argv[i+5];}
for( int i = 0 ; i < nFile ; i++){ inFileName[i] = argv[i + NMINARG -1];}
/// Form outFileName;
TString outFileName = inFileName[0];
@ -59,17 +63,22 @@ int main(int argc, char **argv) {
pos = outFileName.Index("_", pos+1); // find next "_"
if( nFile == 1 ) pos = outFileName.Index("_", pos+1); // find next "_", S/N
outFileName.Remove(pos); // remove the rest
outFileName += "_" + std::to_string(timeWindow);
outFileName += ".root";
printf("-------> Out file name : %s \n", outFileName.Data());
outFileName += "_" + ( timeWindow >= 0 ? std::to_string(timeWindow) : "single");
TString outFileFullName;
outFileFullName = outFileName + ".root";
// uint16_t header = 0; // for caen bin
printf("-------> Out file name : %s \n", outFileFullName.Data());
printf("========================================= Number of Files : %d \n", nFile);
for( int i = 0; i < nFile; i++) printf("%2d | %s \n", i, inFileName[i].Data());
printf("=========================================\n");
printf(" Time Window = %ld ns = %.1f us\n", timeWindow, timeWindow/1000.);
printf(" Include Trace = %s\n", traceOn ? "Yes" : "No");
printf(" Debug level = %d\n", debug);
printf(" Batch size = %d events/file\n", batchSize);
printf(" Max multiplity = %d hits/event (hard coded)\n", MAX_MULTI);
printf(" Time Window = %ld ns = %.1f us\n", timeWindow, timeWindow/1000.);
printf(" Include Trace = %s\n", traceOn ? "Yes" : "No");
printf(" Debug level = %d\n", debug);
printf(" Max multiplity = %d hits/event (hard coded)\n", MAX_MULTI);
if( traceOn ) printf(" Max Trace Length = %d (hard coded)\n", MAX_TRACE_LENGTH);
printf("========================================= Grouping files\n");
std::vector<std::vector<FileInfo>> fileGroupList; // fileName and ID = SN * 1000 + index
@ -79,15 +88,22 @@ int main(int argc, char **argv) {
FSUReader * readerA = new FSUReader(inFileName[0].Data(), 1, 1);
readerA->ScanNumBlock(0,0);
FileInfo fileInfo = {inFileName[0].Data(), readerA->GetSN() * 1000 + readerA->GetFileOrder(), readerA->GetHitCount()};
if( readerA->GetOptimumBatchSize() > batchSize ) batchSize = readerA->GetOptimumBatchSize();
//printf("Hit count : %7ld | opt. batch size : %7ld\n", readerA->GetTotalHitCount(), readerA->GetOptimumBatchSize());
FileInfo fileInfo = {inFileName[0].Data(), readerA->GetSN() * 1000 + readerA->GetFileOrder(), readerA->GetTotalHitCount()};
fileList.push_back(fileInfo);
totalHitCount += readerA->GetHitCount();
totalHitCount += readerA->GetTotalHitCount();
for( int i = 1; i < nFile; i++){
FSUReader * readerB = new FSUReader(inFileName[i].Data(), 1, 0);
FSUReader * readerB = new FSUReader(inFileName[i].Data(), 1, 1);
readerB->ScanNumBlock(0,0);
totalHitCount += readerB->GetHitCount();
fileInfo = {inFileName[i].Data(), readerB->GetSN() * 1000 + readerB->GetFileOrder(), readerB->GetHitCount()};
// if( readerB->GetOptimumBatchSize() > batchSize ) batchSize = readerB->GetOptimumBatchSize();
batchSize = readerB->GetOptimumBatchSize();
//printf("Hit count : %7ld | opt. batch size : %7ld\n", readerB->GetTotalHitCount(), readerB->GetOptimumBatchSize());
totalHitCount += readerB->GetTotalHitCount();
fileInfo = {inFileName[i].Data(), readerB->GetSN() * 1000 + readerB->GetFileOrder(), readerB->GetTotalHitCount()};
if( readerA->GetSN() == readerB->GetSN() ){
fileList.push_back(fileInfo);
@ -104,25 +120,21 @@ int main(int argc, char **argv) {
delete readerA;
printf("======================= total Hit Count : %llu\n", totalHitCount);
printf(">>>>>>>>>>>>>>>>>>>>>>>>>> Batch size : %d events/file\n", batchSize);
for( size_t i = 0; i < fileGroupList.size(); i++){
printf("group ----- %ld \n", i);
//sort by ID
std::sort(fileGroupList[i].begin(), fileGroupList[i].end(), [](const FileInfo & a, const FileInfo & b) {
return a.fileID < b.fileID;
});
for( size_t j = 0; j < fileGroupList[i].size(); j++){
printf("%3ld | %8d | %9lu| %s \n", j, fileGroupList[i][j].fileID, fileGroupList[i][j].hitCount, fileGroupList[i][j].fileName.c_str() );
}
}
// //*====================================== create tree
TFile * outRootFile = new TFile(outFileName, "recreate");
TTree * tree = new TTree("tree", outFileName);
TFile * outRootFile = nullptr;
TTree * tree = nullptr;
unsigned long long evID = 0;
unsigned int multi = 0;
unsigned short sn[MAX_MULTI] = {0}; /// board SN
@ -132,6 +144,11 @@ int main(int argc, char **argv) {
unsigned long long e_t[MAX_MULTI] = {0}; /// timestamp 47 bit
unsigned short e_f[MAX_MULTI] = {0}; /// fine time 10 bit
unsigned short traceLength[MAX_MULTI];
short trace[MAX_MULTI][MAX_TRACE_LENGTH];
// //*====================================== create tree
outRootFile = new TFile(outFileFullName, "recreate");
tree = new TTree("tree", outFileFullName);
tree->Branch("evID", &evID, "event_ID/l");
tree->Branch("multi", &multi, "multi/i");
@ -139,21 +156,17 @@ int main(int argc, char **argv) {
tree->Branch("ch", ch, "ch[multi]/s");
tree->Branch("e", e, "e[multi]/s");
tree->Branch("e2", e2, "e2[multi]/s");
tree->Branch("e_t", e_t, "e_timestamp[multi]/l");
tree->Branch("e_f", e_f, "e_fineTime[multi]/s");
tree->Branch("e_t", e_t, "e_t[multi]/l");
tree->Branch("e_f", e_f, "e_f[multi]/s");
tree->Branch("traceLength", traceLength, "traceLength[multi]/s");
TClonesArray * arrayTrace = nullptr;
TGraph * trace = nullptr;
if( traceOn ) {
arrayTrace = new TClonesArray("TGraph");
tree->Branch("trace", arrayTrace, 2560000);
arrayTrace->BypassStreamer();
tree->Branch("trace", trace,"trace[multi][MAX_TRACE_LENGTH]/S");
tree->GetBranch("trace")->SetCompressionSettings(205);
}
//*======================================= Open files
printf("========================================= Open files & Build Events.\n");
printf("========================================= Open files & reading 1st batch.\n");
const short nGroup = fileGroupList.size();
std::vector<Hit> hitList[nGroup];
@ -165,9 +178,9 @@ int main(int argc, char **argv) {
for( size_t j = 0; j < fileGroupList[i].size(); j++){
fList.push_back( fileGroupList[i][j].fileName );
}
reader[i] = new FSUReader(fList, 600, debug);
hitList[i] = reader[i]->ReadBatch(batchSize, debug );
reader[i]->PrintHitListInfo(hitList[i], "hitList-" + std::to_string(reader[i]->GetSN()));
reader[i] = new FSUReader(fList, 1024, debug); // 1024 is the maximum event / agg.
hitList[i] = reader[i]->ReadBatch(batchSize, traceOn, debug );
reader[i]->PrintHitListInfo(&hitList[i], "hitList-" + std::to_string(reader[i]->GetSN()));
ID[i] = 0;
if( debug ) {
@ -201,6 +214,7 @@ int main(int argc, char **argv) {
std::vector<Hit> events;
unsigned long long hitProcessed = 0;
printf("========================================= Start Building Events....\n");
do{
@ -215,7 +229,8 @@ int main(int argc, char **argv) {
//chekc if reached the end of hitList
if( ID[ig] >= hitList[ig].size() ) {
hitList[ig] = reader[ig]->ReadBatch(batchSize, debug + 1);
hitList[ig] = reader[ig]->ReadBatch(batchSize, traceOn, debug + 1);
if( debug ) reader[ig]->PrintHitListInfo( &hitList[ig], "hitList-" + std::to_string(ig));
ID[ig] = 0;
if( hitList[ig].size() == 0 ) continue;
}
@ -224,8 +239,8 @@ int main(int argc, char **argv) {
do{
if( (long int)(hitList[ig].at(ID[ig]).timestamp - t0) <= timeWindow ){
events.push_back(hitList[ig].at(ID[ig]));
if( (long int)(hitList[ig][ID[ig]].timestamp - t0) <= timeWindow ){
events.push_back(hitList[ig][ID[ig]]);
ID[ig] ++;
}else{
break;
@ -233,7 +248,8 @@ int main(int argc, char **argv) {
//check if reached the end of hitList
if( ID[ig] >= hitList[ig].size() ) {
hitList[ig] = reader[ig]->ReadBatch(batchSize, debug);
hitList[ig] = reader[ig]->ReadBatch(batchSize, traceOn, debug);
if( debug ) reader[ig]->PrintHitListInfo( &hitList[ig], "hitList-" + std::to_string(ig));
ID[ig] = 0;
if( hitList[ig].size() == 0 ) break;
}
@ -258,15 +274,18 @@ int main(int argc, char **argv) {
tEnd = events.back().timestamp;
hitProcessed += events.size();
if( hitProcessed % 10000 == 0 ) printf("hit Porcessed %llu/%llu hit....%.2f%%\n\033[A\r", hitProcessed, totalHitCount, hitProcessed*100./totalHitCount);
if( hitProcessed % (traceOn ? 10000 : 10000) == 0 ) printf("hit Porcessed %llu/%llu hit....%.2f%%\n\033[A\r", hitProcessed, totalHitCount, hitProcessed*100./totalHitCount);
multi = events.size() ;
if( events.size() >= MAX_MULTI ) {
printf("event %lld has size = %d > MAX_MULTI = %d\n", evID, multi, MAX_MULTI);
printf("\033[31m event %lld has size = %d > MAX_MULTI = %d \033[0m\n", evID, multi, MAX_MULTI);
for( int po = 0 ; po < 10 ; po ++){
events[po].Print();
}
multi = MAX_MULTI;
}
if( debug ) printf("=================================== filling data | %u \n", multi);
for( size_t p = 0; p < multi ; p ++ ) {
if( debug ) {printf("%4zu | ", p); events[p].Print();}
@ -279,10 +298,13 @@ int main(int argc, char **argv) {
traceLength[p] = events[p].traceLength;
if( traceOn ){
trace = (TGraph *) arrayTrace->ConstructedAt(multi, "C");
trace->Clear();
for( int hh = 0; hh < traceLength[multi]; hh++){
trace->SetPoint(hh, hh, events[p].trace[hh]);
if( traceLength[p] > MAX_TRACE_LENGTH ) {
printf("\033[31m event %lld has trace length = %d > MAX_TRACE_LENGTH = %d \033[0m\n", evID, traceLength[p], MAX_TRACE_LENGTH);
traceLength[p] = MAX_TRACE_LENGTH;
}
for( int hh = 0; hh < traceLength[p]; hh++){
trace[p][hh] = events[p].trace[hh];
}
}
}
@ -290,6 +312,7 @@ int main(int argc, char **argv) {
outRootFile->cd();
tree->Fill();
// tree->Write();
multi = 0;
evID ++;
@ -314,7 +337,7 @@ int main(int argc, char **argv) {
continue;
}else{
if( ID[i] >= hitList[i].size( )) {
hitList[i] = reader[i]->ReadBatch(batchSize, debug);
hitList[i] = reader[i]->ReadBatch(batchSize, traceOn, debug);
ID[i] = 0;
if( hitList[i].size() == 0 ) nFileFinished ++;
}
@ -330,23 +353,26 @@ int main(int argc, char **argv) {
double runTime = (runEndTime - runStartTime) * 1e-6;
printf("========================================= finished.\n");
printf(" event building time = %.2f sec = %.2f min\n", runTime, runTime/60.);
printf(" total events built = %llu by event builder (%llu in tree)\n", evID, tree->GetEntriesFast());
// printf(" total events built = %llu by event builder (%llu in tree)\n", evID, tree->GetEntriesFast());
printf(" total events built = %llu by event builder\n", evID);
double tDuration_sec = (tEnd - tStart) * 1e-9;
printf(" first timestamp = %20llu ns\n", tStart);
printf(" last timestamp = %20llu ns\n", tEnd);
printf(" total data duration = %.2f sec = %.2f min\n", tDuration_sec, tDuration_sec/60.);
printf("==============> saved to %s \n", outFileName.Data());
printf("========================================> saved to %s \n", outFileFullName.Data());
TMacro info;
info.AddLine(Form("tStart= %20llu ns",tStart));
info.AddLine(Form(" tEnd= %20llu ns",tEnd));
info.Write("info");
outRootFile->Close();
for( int i = 0; i < nGroup; i++) delete reader[i];
delete [] reader;
printf("####################################### end of %s\n", argv[0]);
return 0;
}

305
Aux/FSU2CAEN.cpp Normal file
View File

@ -0,0 +1,305 @@
#include "fsuReader.h"
struct FileInfo{
std::string fileName;
int fileevID;
unsigned long hitCount;
int sn;
int numCh;
int runNum;
};
#define minNARG 3
//^#############################################################
//^#############################################################
int main(int argc, char **argv) {
printf("=========================================\n");
printf("=== *.fsu to CoMPASS bin ===\n");
printf("=========================================\n");
if (argc < minNARG) {
printf("Incorrect number of arguments:\n");
printf("%s [tar] [inFile1] [inFile2] .... \n", argv[0]);
printf(" tar : output tar, 0 = no, 1 = yes \n");
printf("\n");
printf(" Example: %s 0 '\\ls -1 *001*.fsu'\n", argv[0]);
printf("\n\n");
return 1;
}
unsigned int debug = false;
uInt runStartTime = getTime_us();
///============= read input
// long timeWindow = atoi(argv[1]);
// bool traceOn = atoi(argv[2]);
bool tarFlag = atoi(argv[1]);
unsigned int batchSize = 2* DEFAULT_HALFBUFFERSIZE;
int nFile = argc - minNARG + 1;
std::string inFileName[nFile];
for( int i = 0 ; i < nFile ; i++){ inFileName[i] = argv[i+ minNARG - 1];}
printf("========================================= Number of Files : %d \n", nFile);
for( int i = 0; i < nFile; i++) printf("%2d | %s \n", i, inFileName[i].c_str());
printf("=========================================\n");
printf(" Batch size = %d events/file\n", batchSize);
// printf(" Out file name = %s \n", outFileName.c_str());
printf(" Is tar output = %s \n", tarFlag ? "Yes" : "No");
printf("========================================= Grouping files\n");
std::vector<std::vector<FileInfo>> fileGroupList; // fileName and evID = SN * 1000 + index
std::vector<FileInfo> fileList;
unsigned long long int totalHitCount = 0;
FSUReader * readerA = new FSUReader(inFileName[0], 1, 1);
readerA->ScanNumBlock(0,0);
if( readerA->GetOptimumBatchSize() > batchSize ) batchSize = readerA->GetOptimumBatchSize();
FileInfo fileInfo = {inFileName[0], readerA->GetSN() * 1000 + readerA->GetFileOrder(), readerA->GetTotalHitCount(), readerA->GetSN(), readerA->GetNumCh(), readerA->GetRunNum()};
fileList.push_back(fileInfo);
totalHitCount += readerA->GetTotalHitCount();
for( int i = 1; i < nFile; i++){
FSUReader * readerB = new FSUReader(inFileName[i], 1, 1);
readerB->ScanNumBlock(0,0);
if( readerB->GetOptimumBatchSize() > batchSize ) batchSize = readerB->GetOptimumBatchSize();
totalHitCount += readerB->GetTotalHitCount();
fileInfo = {inFileName[i], readerB->GetSN() * 1000 + readerB->GetFileOrder(), readerB->GetTotalHitCount(), readerB->GetSN(), readerB->GetNumCh(), readerB->GetRunNum()};
if( readerA->GetSN() == readerB->GetSN() ){
fileList.push_back(fileInfo);
}else{
fileGroupList.push_back(fileList);
fileList.clear();
fileList.push_back(fileInfo);
}
delete readerA;
readerA = readerB;
}
fileGroupList.push_back(fileList);
delete readerA;
printf("======================= total Hit Count : %llu\n", totalHitCount);
for( size_t i = 0; i < fileGroupList.size(); i++){
printf("group ----- %ld \n", i);
//sort by evID
std::sort(fileGroupList[i].begin(), fileGroupList[i].end(), [](const FileInfo & a, const FileInfo & b) {
return a.fileevID < b.fileevID;
});
for( size_t j = 0; j < fileGroupList[i].size(); j++){
printf("%3ld | %8d | %9lu| %s \n", j, fileGroupList[i][j].fileevID, fileGroupList[i][j].hitCount, fileGroupList[i][j].fileName.c_str() );
}
}
//*====================================== format output files
const short numFileGroup = fileGroupList.size();
FILE ** outFile[numFileGroup];
std::vector<std::string> outFileName[numFileGroup];
std::vector<uint16_t> header[numFileGroup];
std::vector<unsigned int> flags[numFileGroup];
for( int i = 0; i < numFileGroup; i++ ){
outFile[i] = new FILE * [fileGroupList[i][0].numCh];
for( int ch = 0; ch < fileGroupList[i][0].numCh; ch++ ){
std::string dudu = "Data_CH" + std::to_string(ch) + "@DIGI_" + std::to_string(fileGroupList[i][0].sn) + "_run_" + std::to_string(fileGroupList[i][0].runNum) + ".BIN";
// printf("|%s| \n", dudu.c_str());
outFile[i][ch] = fopen(dudu.c_str(), "wb");
outFileName[i].push_back(dudu);
header[i].push_back(0);
flags[i].push_back(0);
}
}
// std::string temp = inFileName[0];
// size_t pos = temp.find('_');
// pos = temp.find('_', pos + 1);
// std::string outFile_prefix = temp.substr(0, pos);
// std::string outFileName = outFile_prefix + ".BIN";
//*======================================= Open files
printf("========================================= Open files & Build Events.\n");
const short nGroup = fileGroupList.size();
std::vector<Hit> hitList[nGroup];
FSUReader ** reader = new FSUReader * [nGroup];
ulong evID[nGroup];
for( short i = 0; i < nGroup; i++){
std::vector<std::string> fList;
for( size_t j = 0; j < fileGroupList[i].size(); j++){
fList.push_back( fileGroupList[i][j].fileName );
}
reader[i] = new FSUReader(fList, 600, debug);
hitList[i] = reader[i]->ReadBatch(batchSize, debug );
reader[i]->PrintHitListInfo(&hitList[i], "hitList-" + std::to_string(reader[i]->GetSN()));
evID[i] = 0;
if( debug ) {
for( size_t p = 0; p < 10; p ++ ){
if( hitList[i].size() <= p ) break;
hitList[i][p].Print();
}
}
}
unsigned long long tStart = 0;
unsigned long long tEnd = 0;
unsigned long long t0 = -1;
short g0 = 0 ;
int nFileFinished = 0;
unsigned long long hitProcessed = 0;
do{
// find the earlist time
t0 = -1;
for( short i = 0; i < nGroup; i++){
if( hitList[i].size() == 0 ) continue;
//chekc if reached the end of hitList
if( evID[i] >= hitList[i].size() ) {
hitList[i] = reader[i]->ReadBatch(batchSize, debug + 1);
if( debug ) reader[i]->PrintHitListInfo( &hitList[i], "hitList-" + std::to_string(i));
evID[i] = 0;
if( hitList[i].size() == 0 ) continue;
}
if( hitList[i][evID[i]].timestamp < t0 ) {
t0 = hitList[i][evID[i]].timestamp;
g0 = i;
}
}
// Set file header
int p_ch = hitList[g0][evID[g0]].ch; // present ch
if( header[g0][p_ch] == 0 ) {
header[g0][p_ch] = 0xCAE1;
if( hitList[g0][evID[g0]].energy2 > 0 ) header[g0][p_ch] += 4;
if( hitList[g0][evID[g0]].traceLength > 0 ) header[g0][p_ch] += 8;
if( hitList[g0][evID[g0]].pileUp ) flags[g0][p_ch] += 0x8000;
if( hitList[g0][evID[g0]].fineTime > 0 ) flags[g0][p_ch] += 0x4000;
fwrite(&(header[g0][p_ch]), 2, 1, outFile[g0][p_ch]);
}
hitList[g0][evID[g0]].WriteHitsToCAENBinary(outFile[g0][p_ch], header[g0][p_ch]);
// fwrite(&(hitList[g0][evID[g0]].sn), 2, 1, outFile);
// fwrite(&(hitList[g0][evID[g0]].ch), 2, 1, outFile);
// unsigned psTimestamp = hitList[g0][evID[g0]].timestamp * 1000 + hitList[g0][evID[g0]].fineTime;
// fwrite(&(psTimestamp), 8, 1, outFile);
// fwrite(&(hitList[g0][evID[g0]].energy), 2, 1, outFile);
// if( hitList[g0][evID[g0]].energy2 > 0 ) fwrite(&(hitList[g0][evID[g0]].energy2), 2, 1, outFile);
// fwrite(&(flags), 4, 1, outFile);
// if( hitList[g0][evID[g0]].traceLength > 0 ){
// char waveCode = 1;
// fwrite(&(waveCode), 1, 1, outFile);
// fwrite(&(hitList[g0][evID[g0]].traceLength), 4, 1, outFile);
// for( int i = 0; i < hitList[g0][evID[g0]].traceLength; i++ ){
// fwrite(&(hitList[g0][evID[g0]].trace[i]), 2, 1, outFile);
// }
// }
evID[g0]++;
if( hitProcessed == 0) tStart = hitList[g0][evID[g0]].timestamp;
hitProcessed ++;
if( hitProcessed % 10000 == 0 ) printf("hit Porcessed %llu/%llu hit....%.2f%%\n\033[A\r", hitProcessed, totalHitCount, hitProcessed*100./totalHitCount);
if( hitProcessed == totalHitCount -1 ) tEnd = hitList[g0][evID[g0]].timestamp;
//*=============
nFileFinished = 0;
for( int i = 0 ; i < nGroup; i++) {
if( hitList[i].size() == 0 ) {
nFileFinished ++;
continue;
}else{
if( evID[i] >= hitList[i].size( )) {
hitList[i] = reader[i]->ReadBatch(batchSize, debug);
evID[i] = 0;
if( hitList[i].size() == 0 ) nFileFinished ++;
}
}
}
if( debug > 1 ) printf("========== nFileFinished : %d\n", nFileFinished);
}while( nFileFinished < nGroup);
uInt runEndTime = getTime_us();
double runTime = (runEndTime - runStartTime) * 1e-6;
printf("========================================= finished.\n");
printf(" event building time = %.2f sec = %.2f min\n", runTime, runTime/60.);
printf(" total hit = %llu \n", hitProcessed);
double tDuration_sec = (tEnd - tStart) * 1e-9;
printf(" first timestamp = %20llu ns\n", tStart);
printf(" last timestamp = %20llu ns\n", tEnd);
printf(" total data duration = %.2f sec = %.2f min\n", tDuration_sec, tDuration_sec/60.);
for( int i = 0; i < nGroup; i++) delete reader[i];
delete [] reader;
//============================== delete empty files and close FILE
std::vector<std::string> nonEmptyFileList;
printf("================= Removing Empty Files ....\n");
printf("============================> saved to ....");
if( tarFlag == false ) printf("\n");
for( int i = 0; i < numFileGroup; i++ ){
for( int ch = 0; ch < fileGroupList[i][0].numCh; ch++){
if( ftell(outFile[i][ch]) == 0 ){
int dummy = std::system(("rm -f " + outFileName[i][ch]).c_str());
// printf("Remove %s.\n", outFileName[i][ch].c_str());
}else{
nonEmptyFileList.push_back(outFileName[i][ch]);
if( tarFlag == false ) printf("%s\n", outFileName[i][ch].c_str());
}
}
}
if( tarFlag ){
std::string tarFileName = "run_" + std::to_string(fileGroupList[0][0].runNum) + ".tar.gz";
printf("%s\n", tarFileName.c_str());
printf("============================> tar.gz the BIN\n");
std::string command = "tar -czf " + tarFileName + " ";
for( size_t i = 0; i < nonEmptyFileList.size(); i++ ){
command += nonEmptyFileList[i] + " ";
}
int result = std::system(command.c_str());
if (result == 0) {
printf("Archive created successfully: %s\n", tarFileName.c_str());
for( size_t i = 0; i < nonEmptyFileList.size(); i++ ){
int dummy = std::system(("rm -f " + nonEmptyFileList[i]).c_str());
// printf("Remove %s.\n", nonEmptyFileList[i].c_str());
}
} else {
printf("Error creating archive\n");
}
}
printf("============================================== end of program\n");
return 0;
}

View File

@ -5,16 +5,16 @@
CC = g++
#COPTS = -fPIC -DLINUX -O2 -std=c++17 -lpthread
COPTS = -fPIC -DLINUX -g -O0 -Wall -std=c++17 -lpthread
COPTS = -fPIC -DLINUX -O2 -std=c++17 -lpthread
# COPTS = -fPIC -DLINUX -g -O0 -Wall -std=c++17 -lpthread
CAENLIBS = -lCAENDigitizer -lCAENVME
ROOTLIBS = `root-config --cflags --glibs`
OBJS = ClassDigitizer.o MultiBuilder.o ClassInfluxDB.o
OBJS = ClassDigitizer.o MultiBuilder.o ClassInfluxDB.o ClassDigitizerAPI.o
ALL = test EventBuilder DataReader DumpFSU2ROOT SettingsExplorer
ALL = test EventBuilder DataReader DumpFSU2ROOT SettingsExplorer FSU2CAEN haha
#########################################################################
@ -29,12 +29,15 @@ MultiBuilder.o : ../MultiBuilder.cpp ../MultiBuilder.h ../Hit.h
ClassDigitizer.o : ../ClassDigitizer.cpp ../ClassDigitizer.h ../RegisterAddress.h ../macro.h ../ClassData.h
$(CC) $(COPTS) -c ../ClassDigitizer.cpp
ClassDigitizerAPI.o : ../ClassDigitizer.cpp ClassDigitizerAPI.cpp ../ClassDigitizer.h ../RegisterAddress.h ../macro.h ../ClassData.h
$(CC) $(COPTS) -c ClassDigitizerAPI.cpp
ClassInfluxDB.o : ../ClassInfluxDB.cpp ../ClassInfluxDB.h
$(CC) $(COPTS) -c ../ClassInfluxDB.cpp -lcurl
test : test.cpp ../ClassDigitizer.o ../MultiBuilder.o ../ClassInfluxDB.o
test : test.cpp ../ClassDigitizer.o ../MultiBuilder.o ../ClassInfluxDB.o ClassDigitizerAPI.o
@echo "--------- making test"
$(CC) $(COPTS) -o test test.cpp ../ClassDigitizer.o ../MultiBuilder.o ../ClassInfluxDB.o $(CAENLIBS) $(ROOTLIBS) -lcurl
$(CC) -fPIC -DLINUX -O0 -std=c++17 -lpthread -g -o test test.cpp ../ClassDigitizer.o ClassDigitizerAPI.o ../MultiBuilder.o ../ClassInfluxDB.o $(CAENLIBS) $(ROOTLIBS) -lcurl
# test_indep : test_indep.cpp ../RegisterAddress.h ../macro.h
# @echo "--------- making test_indep"
@ -44,17 +47,13 @@ DataReader : DataReaderScript.cpp ../ClassData.h MultiBuilder.o
@echo "--------- making DataReader"
$(CC) $(COPTS) -o DataReader DataReaderScript.cpp ../ClassData.h MultiBuilder.o
# EventBuilder_old : EventBuilder_old.cpp ../ClassData.h MultiBuilder.o fsuReader.h
# @echo "--------- making EventBuilder"
# $(CC) $(COPTS) -o EventBuilder_old EventBuilder_old.cpp MultiBuilder.o $(ROOTLIBS)
EventBuilder : EventBuilder.cpp ../ClassData.h fsuReader.h ../Hit.h
@echo "--------- making EventBuilder"
$(CC) $(COPTS) -o EventBuilder EventBuilder.cpp $(ROOTLIBS)
# EventBuilderNoTrace : EventBuilderNoTrace.cpp ../ClassData.h fsuReader.h ../Hit.h
# @echo "--------- making EventBuilderNoTrace"
# $(CC) $(COPTS) -o EventBuilderNoTrace EventBuilderNoTrace.cpp $(ROOTLIBS)
FSU2CAEN : FSU2CAEN.cpp ../ClassData.h fsuReader.h ../Hit.h
@echo "--------- making FSU2CAEN"
$(CC) $(COPTS) -o FSU2CAEN FSU2CAEN.cpp
DumpFSU2ROOT : DumpFSU2ROOT.cpp ../ClassData.h MultiBuilder.o
@echo "--------- making DumpFSU2ROOT"

View File

@ -37,18 +37,16 @@ With this approach, it is guaranteed that the output hitList_A is always time-so
This defines the EventBuilder. The arguments are
```sh
./EventBuilder [timeWindow] [withTrace] [verbose] [batchSize] [inFile1] [inFile2] ....
./EventBuilder [timeWindow] [withTrace] [inFile1] [inFile2] ....
timeWindow : in ns, -1 = no event building
withTrace : 0 for no trace, 1 for trace
verbose : > 0 for debug
batchSize : the size of hit in a batch
Output file name is contructed from inFile1
```
as an example,
```sh
/EventBuilder 0 0 0 1000000 '\ls -1 test_001*.fsu'
/EventBuilder 0 0'\ls -1 test_001*.fsu'
```
setting the timeWindow to be -1, will split out a timesorted Hit.
@ -115,6 +113,16 @@ Evenbuilder output is standard information, an example structure is
*............................................................................*
```
# FSU2CAEN.cpp
This convert the *.fsu to Data_CHXX@DIGI_YYYYY_run_ZZ.BIN. the BIN is CoMPASS format and could be useful for couple with existing analysis routine.
```sh
./FSU2CAEN [tarFlag] [inFile1] [inFile2] ....
targFlag : if 1, tar ball all output files.
```
# SettingsExplorer.cpp

View File

@ -64,13 +64,14 @@ void keyPressCommand(){
if( RegList[i].GetRWType() == RW::ReadONLY ) typeStr = "R ";
if( RegList[i].GetRWType() == RW::WriteONLY ) typeStr = " W";
unsigned int value = digi->GetSettingFromMemory(RegList[i], 0);
printf("%2d | 0x%04X %30s %s 0x%08X = %u\n", i,
printf("%2d | 0x%04X %30s %s 0x%08X = %10u\n", i,
RegList[i].GetAddress(),
RegList[i].GetNameChar(),
typeStr.c_str(),
digi->GetSettingFromMemory(RegList[i], 0),
digi->GetSettingFromMemory(RegList[i], 0));
value,
value);
}
std::string input = "-1";
@ -143,12 +144,15 @@ void keyPressCommand(){
RegList[i].ActualAddress(ch);
printf("%2d | 0x%04X %30s %s 0x%08X = %u\n", i,
unsigned int value = digi->GetSettingFromMemory(RegList[i], ch);
printf("%2d | 0x%04X %30s %s 0x%08X = %10u : %d\n", i,
RegList[i].GetAddress(),
RegList[i].GetNameChar(),
typeStr.c_str(),
digi->GetSettingFromMemory(RegList[i], ch),
digi->GetSettingFromMemory(RegList[i], ch));
value,
value,
value * abs(RegList[i].GetPartialStep()));
}
do{

274
Aux/SplitPolePlotter.C Normal file
View File

@ -0,0 +1,274 @@
#ifndef SPLITPOLEPLOTTER
#define SPLITPOLEPLOTTER
#include "TFile.h"
#include "TChain.h"
#include "TH1F.h"
#include "TTreeReader.h"
#include "TTreeReaderValue.h"
#include "TTreeReaderArray.h"
#include "TClonesArray.h"
#include "TGraph.h"
#include "TCutG.h"
#include "TH2.h"
#include "TCanvas.h"
#include "TStyle.h"
#include "TStopwatch.h"
#include "TMath.h"
#include "vector"
#include "../analyzers/SplitPoleHit.h"
namespace ChMap{
const short ScinR = 0;
const short ScinL = 1;
const short dFR = 9;
const short dFL = 8;
const short dBR = 11;
const short dBL = 10;
const short Cathode = 7;
const short AnodeF = 13;
const short AnodeB = 15;
};
const double c = 299.792458; // mm/ns
const double pi = M_PI;
const double deg2rad = pi/180.;
SplitPoleHit hit;
TH2F * PID;
TH2F * coin;
TH1F * hMulti;
TH1F * hF;
TH1F * hB;
TH1F * hXavg;
TH2F * hFocal;
TH2F * hXavg_Q;
TH2F * hXavg_Theta;
TH2F * hRay;
TH1F * hEx;
TH2F * hEx_Multi;
ULong64_t t1, t2;
#define XMIN -200
#define XMAX 200
//^###########################################
void SplitPolePlotter(TChain *tree, TCutG * pidCut = nullptr, double rhoOffset = 0, double rhoScaling = 1, bool isFSUDAQ = true){
printf("#####################################################################\n");
printf("################# SplitPolePlotter.C ####################\n");
printf("#####################################################################\n");
TObjArray * fileList = tree->GetListOfFiles();
printf("\033[0;31m========================================== Number of Files : %2d\n",fileList->GetEntries());
fileList->Print();
printf("========================================== Number of Files : %2d\033[0m\n",fileList->GetEntries());
printf("///////////////////////////////////////////////////////////////////\n");
printf(" Total Number of entries : %llu \n", tree->GetEntries());
printf("///////////////////////////////////////////////////////////////////\n");
if( tree->GetEntries() == 0 ) {
printf("========= no events. Abort.\n");
return;
}
//*====================================================== histograms
coin = new TH2F("hCoin", "Coincident ", 16, 0, 16, 16, 0, 16);
hMulti = new TH1F("hMulti", "Multiplicity", 16, 0, 16);
if( isFSUDAQ ){
PID = new TH2F("hPID", "PID; Scin_X ; AnodeB", 200, 0, 20000, 100, 0, 40000);
hXavg_Q = new TH2F("hXavg_Q", "Xavg vs Q ", 200, XMIN, XMAX, 200, 0, 40000);
}else{
PID = new TH2F("hPID", "PID; Scin_X ; AnodeB", 200, 0, 4000, 100, 0, 5000);
hXavg_Q = new TH2F("hXavg_Q", "Xavg vs Q ", 200, XMIN, XMAX, 200, 0, 5000);
}
hF = new TH1F("hF", "Front delay line position", 600, XMIN, XMAX);
hB = new TH1F("hB", "Back delay line position", 600, XMIN, XMAX);
hXavg = new TH1F("hAvg", "Xavg", 600, XMIN, XMAX);
hFocal = new TH2F("hFocal", "Front vs Back ", 200, XMIN, XMAX, 200, XMIN, XMAX);
hXavg_Theta = new TH2F("hXavg_Theta", "Xavg vs Theta ", 200, XMIN, XMAX, 200, 0.5, 1.4);
hRay = new TH2F("hRay", "Ray plot", 400, XMIN, XMAX, 400, -50, 50);
hEx = new TH1F("hEx", "Ex; Ex [MeV]; count/10 keV", 600, -1, 5);
hEx_Multi = new TH2F("hEx_Multi", "Ex vs Multi; Ex; Multi", 600, -1, 5, 16, 0, 16);
hit.SetMassTablePath("../analyzers/mass20.txt");
hit.CalConstants("12C", "d", "p", 16, 18); // 80MeV, 5 deg
hit.CalZoffset(0.750); // 1.41 T
t1 = 0;
t2 = 0;
//*====================================================== Tree Reader
TTreeReader reader(tree);
TTreeReaderValue<ULong64_t> evID = {reader, "evID"};
TTreeReaderValue<UInt_t> multi = {reader, "multi"};
TTreeReaderArray<UShort_t> sn = {reader, "sn"};
TTreeReaderArray<UShort_t> ch = {reader, "ch"};
TTreeReaderArray<UShort_t> e = {reader, "e"};
TTreeReaderArray<UShort_t> e2 = {reader, "e2"};
TTreeReaderArray<ULong64_t> e_t = {reader, "e_t"};
TTreeReaderArray<UShort_t> e_f = {reader, "e_f"};
ULong64_t NumEntries = tree->GetEntries();
//^###########################################################
//^ * Process
//^###########################################################
printf("############################################### Processing...\n");
fflush(stdout); // flush out any printf
ULong64_t processedEntries = 0;
float Frac = 0.1;
TStopwatch StpWatch;
StpWatch.Start();
while (reader.Next()) {
// if( processedEntries > 10 ) break;
// printf("============== %5llu | multi : %d (%zu) \n", processedEntries, multi.Get()[0], sn.GetSize());
// for( int i = 0; i < multi.Get()[0]; i++ ){
// printf(" %d | %5d %2d %7d %10llu\n", i, sn[i], ch[i], e[i], e_t[i]);
// }
hit.ClearData();
hMulti->Fill(*multi);
// if( *multi != 9 ) continue;
for( int i = 0; i < *multi; i++){
t2 = e_t[i];
if( t2 < t1 ) printf("entry %lld-%d, timestamp is not in order. %llu, %llu\n", processedEntries, i, t2, t1);
if( i == 0 ) t1 = e_t[i];
// if( e[i] == 65535 ) continue;
if( ch[i] == ChMap::ScinR ) {hit.eSR = e[i]; hit.tSR = e_t[i] + e_f[i]/1000;}
if( ch[i] == ChMap::ScinL ) {hit.eSL = e[i]; hit.tSL = e_t[i] + e_f[i]/1000;}
if( ch[i] == ChMap::dFR ) {hit.eFR = e[i]; hit.tFR = e_t[i] + e_f[i]/1000;}
if( ch[i] == ChMap::dFL ) {hit.eFL = e[i]; hit.tFL = e_t[i] + e_f[i]/1000;}
if( ch[i] == ChMap::dBR ) {hit.eBR = e[i]; hit.tBR = e_t[i] + e_f[i]/1000;}
if( ch[i] == ChMap::dBL ) {hit.eBL = e[i]; hit.tBL = e_t[i] + e_f[i]/1000;}
if( ch[i] == ChMap::Cathode ) {hit.eCath = e[i]; hit.tCath = e_t[i] + e_f[i]/1000;}
if( ch[i] == ChMap::AnodeF ) {hit.eAF = e[i]; hit.tAF = e_t[i] + e_f[i]/1000;}
if( ch[i] == ChMap::AnodeB ) {hit.eAB = e[i]; hit.tAB = e_t[i] + e_f[i]/1000;}
for( int j = i+1; j < sn.GetSize(); j++){
coin->Fill(ch[i], ch[j]);
}
}
unsigned int dQ = hit.eAB; // delta Q
unsigned int Qt = hit.eSL; // total Q
if( Qt > 0 && dQ > 0 ) {
PID->Fill(Qt, dQ);
}
//=============== PID gate cut
if( pidCut ){
if( !pidCut->IsInside(Qt, dQ) ) continue;
}
hit.CalData(2);
if( hit.theta > 1.2 || 0.5 > hit.theta ) continue;
if( (!TMath::IsNaN(hit.x1) || !TMath::IsNaN(hit.x2)) ) {
hFocal->Fill(hit.x1, hit.x2);
hF->Fill(hit.x1);
hB->Fill(hit.x2);
hXavg->Fill(hit.xAvg);
hXavg_Q->Fill(hit.xAvg, dQ);
hXavg_Theta->Fill( hit.xAvg, hit.theta);
for( int i = 0; i < 400; i++){
double z = -50 + 100/400.*i;
double x = (z/42.8625 + 0.5)* ( hit.x2-hit.x1) + hit.x1;
hRay->Fill(x,z);
}
double ex = hit.Rho2Ex( ((hit.xAvg - rhoOffset)/1000/rhoScaling + hit.GetRho0() ) );
//if( XMIN < hit.xAvg && hit.xAvg < XMAX) printf("x1 : %6.2f, x2 : %6.2f, xAvg %6.2f cm , ex : %f \n", hit.x1, hit.x2, hit.xAvg, ex);
hEx->Fill(ex);
hEx_Multi->Fill(ex, *multi);
}
//*============================================ Progress Bar
processedEntries ++;
if (processedEntries >= NumEntries*Frac - 1 ) {
TString msg; msg.Form("%llu", NumEntries/1000);
int len = msg.Sizeof();
printf(" %3.0f%% (%*llu/%llu k) processed in %6.1f sec | expect %6.1f sec\n",
Frac*100, len, processedEntries/1000,NumEntries/1000,StpWatch.RealTime(), StpWatch.RealTime()/Frac);
fflush(stdout);
StpWatch.Start(kFALSE);
Frac += 0.1;
}
}
//^###########################################################
//^ * Plot
//^###########################################################
TCanvas * canvas = new TCanvas("cc", "Split-Pole", 2500, 1000);
gStyle->SetOptStat("neiou");
canvas->Divide(5, 2);
canvas->cd(1); {
PID->Draw("colz");
if( pidCut ) pidCut->Draw("same");
}
canvas->cd(2); hRay->Draw("colz");
canvas->cd(3); hF->Draw();
canvas->cd(4); hB->Draw();
canvas->cd(5); hXavg_Q->Draw("colz");
canvas->cd(6); hXavg->Draw("colz");
canvas->cd(7); hEx->Draw();
//canvas->cd(8); coin->Draw("colz");
canvas->cd(8); hEx_Multi->Draw("colz");
canvas->cd(9); canvas->cd(9)->SetLogy(); hMulti->Draw();
canvas->cd(10); hXavg_Theta->Draw("colz");
}
#endif

194
Aux/SplitPolePlotter_MT.C Normal file
View File

@ -0,0 +1,194 @@
#include <TROOT.h>
#include "TTreeReader.h"
#include "TTreeReaderValue.h"
#include "TTreeReaderArray.h"
#include <ROOT/TTreeProcessorMP.hxx>
#include <ROOT/TTreeProcessorMT.hxx>
#include "ROOT/TProcessExecutor.hxx"
#include "ROOT/TThreadedObject.hxx"
#include "TH2F.h"
#include "TH1F.h"
#include "TCutG.h"
#include "TCanvas.h"
#include "SplitPolePlotter.C"
#include "../analyzers/SplitPoleHit.h"
void SplotPolePlotter_MT(TChain * chain, const int nThread, TCutG * pidCut = nullptr, double rhoOffset = 0, double rhoScaling = 1, bool isFSUDAQ = true){
//^====================== Thread Object, destoryed when merge
ROOT::TThreadedObject<TH2F> pCoin("hCoin", "Coincident ", 16, 0, 16, 16, 0, 16);
ROOT::TThreadedObject<TH1F> phMulti("hMulti", "Multiplicity", 16, 0, 16);
ROOT::TThreadedObject<TH2F> pPID("hPID", "PID; Scin_X ; AnodeB", 200, 0, 20000, 100, 0, isFSUDAQ ? 40000 : 5000);
ROOT::TThreadedObject<TH2F> phXavg_Q("hXavg_Q", "Xavg vs Q ", 200, XMIN, XMAX, 200, 0, isFSUDAQ ? 40000 : 5000);
ROOT::TThreadedObject<TH1F> phF("hF", "Front delay line position", 600, XMIN, XMAX);
ROOT::TThreadedObject<TH1F> phB("hB", "Back delay line position", 600, XMIN, XMAX);
ROOT::TThreadedObject<TH1F> phXavg("hAvg", "Xavg", 600, XMIN, XMAX);
ROOT::TThreadedObject<TH2F> phFocal("hFocal", "Front vs Back ", 200, XMIN, XMAX, 200, XMIN, XMAX);
ROOT::TThreadedObject<TH2F> phXavg_Theta("hXavg_Theta", "Xavg vs Theta ", 200, XMIN, XMAX, 200, 0.5, 1.4);
ROOT::TThreadedObject<TH2F> phRay("hRay", "Ray plot", 400, XMIN, XMAX, 400, -50, 50);
ROOT::TThreadedObject<TH1F> phEx("hEx", "Ex; Ex [MeV]; count/10 keV", 600, -1, 5);
ROOT::TThreadedObject<TH2F> phEx_Multi("hEx_Multi", "Ex vs Multi; Ex; Multi", 600, -1, 5, 16, 0, 16);
//^==================== TTreeProcessorMT
ROOT::EnableImplicitMT(nThread);
std::vector<std::string_view> fileList_view;
std::vector<std::string> fileList;
for( int k = 0; k < chain->GetNtrees(); k++){
fileList_view.push_back(chain->GetListOfFiles()->At(k)->GetTitle());
fileList.push_back(chain->GetListOfFiles()->At(k)->GetTitle());
}
ROOT::TTreeProcessorMT tp(fileList_view, "tree");
// tp.SetTasksPerWorkerHint(1);
std::mutex mutex;
int count = 0;
//^======================= Define process
auto ProcessTask = [&](TTreeReader &reader){
TTreeReaderValue<ULong64_t> evID = {reader, "evID"};
TTreeReaderValue<UInt_t> multi = {reader, "multi"};
TTreeReaderArray<UShort_t> sn = {reader, "sn"};
TTreeReaderArray<UShort_t> ch = {reader, "ch"};
TTreeReaderArray<UShort_t> e = {reader, "e"};
TTreeReaderArray<UShort_t> e2 = {reader, "e2"};
TTreeReaderArray<ULong64_t> e_t = {reader, "e_t"};
TTreeReaderArray<UShort_t> e_f = {reader, "e_f"};
mutex.lock();
count++;
printf("-------------- Thread_ID: %d \n", count);
mutex.unlock();
SplitPoleHit hit;
hit.SetMassTablePath("../analyzers/mass20.txt");
hit.CalConstants("12C", "d", "p", 16, 18); // 80MeV, 5 deg
hit.CalZoffset(0.750); // 1.41 T
while (reader.Next()) {
hit.ClearData();
phMulti->Fill(*multi);
// if( *multi != 9 ) continue;
for( int i = 0; i < *multi; i++){
// t2 = e_t[i];
// if( t2 < t1 ) printf("entry %lld-%d, timestamp is not in order. %llu, %llu\n", processedEntries, i, t2, t1);
if( i == 0 ) t1 = e_t[i];
// if( e[i] == 65535 ) continue;
if( ch[i] == ChMap::ScinR ) {hit.eSR = e[i]; hit.tSR = e_t[i] + e_f[i]/1000;}
if( ch[i] == ChMap::ScinL ) {hit.eSL = e[i]; hit.tSL = e_t[i] + e_f[i]/1000;}
if( ch[i] == ChMap::dFR ) {hit.eFR = e[i]; hit.tFR = e_t[i] + e_f[i]/1000;}
if( ch[i] == ChMap::dFL ) {hit.eFL = e[i]; hit.tFL = e_t[i] + e_f[i]/1000;}
if( ch[i] == ChMap::dBR ) {hit.eBR = e[i]; hit.tBR = e_t[i] + e_f[i]/1000;}
if( ch[i] == ChMap::dBL ) {hit.eBL = e[i]; hit.tBL = e_t[i] + e_f[i]/1000;}
if( ch[i] == ChMap::Cathode ) {hit.eCath = e[i]; hit.tCath = e_t[i] + e_f[i]/1000;}
if( ch[i] == ChMap::AnodeF ) {hit.eAF = e[i]; hit.tAF = e_t[i] + e_f[i]/1000;}
if( ch[i] == ChMap::AnodeB ) {hit.eAB = e[i]; hit.tAB = e_t[i] + e_f[i]/1000;}
for( int j = i+1; j < sn.GetSize(); j++){
pCoin->Fill(ch[i], ch[j]);
}
}
unsigned int dQ = hit.eAB; // delta Q
unsigned int Qt = hit.eSL; // total Q
if( Qt > 0 && dQ > 0 ) {
pPID->Fill(Qt, dQ);
}
//=============== PID gate cut
if( pidCut ){
if( !pidCut->IsInside(Qt, dQ) ) continue;
}
hit.CalData(2);
if( hit.theta > 1.2 || 0.5 > hit.theta ) continue;
if( (!TMath::IsNaN(hit.x1) || !TMath::IsNaN(hit.x2)) ) {
phFocal->Fill(hit.x1, hit.x2);
phF->Fill(hit.x1);
phB->Fill(hit.x2);
phXavg->Fill(hit.xAvg);
phXavg_Q->Fill(hit.xAvg, dQ);
phXavg_Theta->Fill( hit.xAvg, hit.theta);
for( int i = 0; i < 400; i++){
double z = -50 + 100/400.*i;
double x = (z/42.8625 + 0.5)* ( hit.x2-hit.x1) + hit.x1;
phRay->Fill(x,z);
}
double ex = hit.Rho2Ex( ((hit.xAvg - rhoOffset)/1000/rhoScaling + hit.GetRho0() ) );
//if( XMIN < hit.xAvg && hit.xAvg < XMAX) printf("x1 : %6.2f, x2 : %6.2f, xAvg %6.2f cm , ex : %f \n", hit.x1, hit.x2, hit.xAvg, ex);
phEx->Fill(ex);
phEx_Multi->Fill(ex, *multi);
}
}
return 0;
};
//^============================ Run TP
tp.Process(ProcessTask);
//^============================ Merge all ThreadedObject
auto coin = pCoin.Merge();
auto hMulti= phMulti.Merge();
auto hEx = phEx.Merge();
auto hEx_Multi = phEx_Multi.Merge();
auto PID = pPID.Merge();
auto hFocal = phFocal.Merge();
auto hF = phF.Merge();
auto hB = phB.Merge();
auto hXavg = phXavg.Merge();
auto hXavg_Q = phXavg_Q.Merge();
auto hXavg_Theta = phXavg_Theta.Merge();
auto hRay = phRay.Merge();
//^============================== Plot
gStyle->SetOptStat("neiou");
TCanvas * canvas = new TCanvas("cc", "Split-Pole", 2500, 1000);
canvas->Divide(5, 2);
canvas->cd(1); {
PID->DrawCopy("colz");
if( pidCut ) pidCut->Draw("same");
}
canvas->cd(2); hRay->DrawCopy("colz");
canvas->cd(3); hF->DrawCopy();
canvas->cd(4); hB->DrawCopy();
canvas->cd(5); hXavg_Q->DrawCopy("colz");
canvas->cd(6); hXavg->DrawCopy("colz");
canvas->cd(7); hEx->DrawCopy();
//canvas->cd(8); coin->DrawCopy("colz");
canvas->cd(8); hEx_Multi->DrawCopy("colz");
canvas->cd(9); canvas->cd(9)->SetLogy(); hMulti->DrawCopy();
canvas->cd(10); hXavg_Theta->DrawCopy("colz");
}

View File

@ -3,7 +3,7 @@
#include <algorithm>
#include <filesystem>
// #include "AggSeparator.h"
#define DEFAULT_HALFBUFFERSIZE 5000000
class FSUReader{
@ -49,6 +49,7 @@ class FSUReader{
int GetNumCh() const{return numCh;}
int GetFileOrder() const{return order;}
int GetChMask() const{return chMask;}
int GetRunNum() const{return runNum;}
unsigned long GetFileByteSize() const {return inFileSize;}
void ClearHitList() { hit.clear();}
@ -60,32 +61,25 @@ class FSUReader{
return hit[id];
}
void ClearHitCount() {hitCount = 0;}
ulong GetHitCount() const{return hitCount;}
void ClearTotalHitCount() {totalHitCount = 0;}
ulong GetTotalHitCount() const{return totalHitCount;}
std::vector<Hit> ReadBatch(unsigned int batchSize = 1000000, bool verbose = false); // output the sorted Hit
// std::string SaveHit(std::vector<Hit> hitList, bool isAppend = false);
// std::string SaveHit2NewFile(std::string saveFolder = "./", std::string indexStr = "");
// void SortAndSaveTS(unsigned int batchSize = 1000000, bool verbose = false);
// off_t GetTSFileSize() const {return tsFileSize;}
//TODO
//void SplitFile(unsigned long hitSizePreFile);
std::vector<Hit> ReadBatch(unsigned int batchSize = 1000000, bool traceOn = false, bool verbose = false); // output the sorted Hit
void PrintHit(ulong numHit = -1, ulong startIndex = 0) {
for( ulong i = startIndex; i < std::min(numHit, hitCount); i++){
for( ulong i = startIndex; i < std::min(numHit, totalHitCount); i++){
printf("%10zu ", i); hit[i].Print();
}
}
static void PrintHitListInfo(std::vector<Hit> hitList, std::string name){
size_t n = hitList.size();
static void PrintHitListInfo(std::vector<Hit> * hitList, std::string name){
size_t n = hitList->size();
size_t s = sizeof(Hit);
printf("============== %s, size : %zu | %.2f MByte\n", name.c_str(), n, n*s/1024./1024.);
if( n > 0 ){
printf("t0 : %15llu \n", hitList.at(0).timestamp);
printf("t1 : %15llu \n", hitList.back().timestamp);
printf("t0 : %15llu ns\n", hitList->front().timestamp);
printf("t1 : %15llu ns\n", hitList->back().timestamp);
printf("dt : %15.3f ms\n", (hitList->back().timestamp - hitList->front().timestamp)/1e6);
}
}
@ -94,13 +88,13 @@ class FSUReader{
size_t s = sizeof(Hit);
printf("============== reader.hit, size : %zu | %.2f MByte\n", n, n*s/1024./1024.);
if( n > 0 ){
printf("t0 : %15llu \n", hit.at(0).timestamp);
printf("t1 : %15llu \n", hit.back().timestamp);
printf("t0 : %15llu ns\n", hit.at(0).timestamp);
printf("t1 : %15llu ns\n", hit.back().timestamp);
printf("dt : %15.3f ms\n", (hit.back().timestamp - hit.front().timestamp)/1e6);
}
}
//void SaveAsCAENCoMPASSFormat();
unsigned long GetOptimumBatchSize() const {return optBufferSize;}
private:
@ -123,11 +117,12 @@ class FSUReader{
uShort order;
uShort chMask;
uShort numCh;
uShort runNum;
std::vector<unsigned int> blockPos;
std::vector<unsigned int > blockTimeStamp;
unsigned long hitCount;
unsigned long totalHitCount;
std::vector<Hit> hit;
@ -137,8 +132,15 @@ class FSUReader{
off_t tsFileSize;
//checking the t0 and tmin for every 1 million hit
unsigned short nMillion;
std::vector<unsigned long> tmin;
unsigned long optBufferSize;
};
//^==============================================================
inline FSUReader::~FSUReader(){
delete data;
@ -146,6 +148,7 @@ inline FSUReader::~FSUReader(){
}
//^==============================================================
inline FSUReader::FSUReader(){
inFile = nullptr;
data = nullptr;
@ -159,6 +162,7 @@ inline FSUReader::FSUReader(){
}
//^==============================================================
inline FSUReader::FSUReader(std::string fileName, uInt dataSize, int verbose){
inFile = nullptr;
data = nullptr;
@ -172,6 +176,7 @@ inline FSUReader::FSUReader(std::string fileName, uInt dataSize, int verbose){
OpenFile(fileName, dataSize, verbose);
}
//^==============================================================
inline FSUReader::FSUReader(std::vector<std::string> fileList, uInt dataSize, int verbose){
inFile = nullptr;
data = nullptr;
@ -186,6 +191,7 @@ inline FSUReader::FSUReader(std::vector<std::string> fileList, uInt dataSize, in
}
//^==============================================================
inline void FSUReader::OpenFile(std::string fileName, uInt dataSize, int verbose){
/// File format must be YYY...Y_runXXX_AAA_BBB_TT_CCC.fsu
@ -221,9 +227,14 @@ inline void FSUReader::OpenFile(std::string fileName, uInt dataSize, int verbose
blockPos.clear();
blockTimeStamp.clear();
hitCount = 0;
totalHitCount = 0;
hit.clear();
nMillion = 0;
tmin.clear();
tmin.push_back(-1);
optBufferSize = 2*DEFAULT_HALFBUFFERSIZE;
//check is the file is *.fsu or *.fsu.X
size_t found = fileName.find_last_of('.');
std::string ext = fileName.substr(found + 1);
@ -253,14 +264,17 @@ inline void FSUReader::OpenFile(std::string fileName, uInt dataSize, int verbose
std::string token;
while (std::getline(iss, token, '_')) { tokens.push_back(token); }
sn = atoi(tokens[2].c_str());
tick2ns = atoi(tokens[4].c_str());
order = atoi(tokens[5].c_str());
short token_size = tokens.size();
// for( short i = 0; i < token_size; i ++ ) printf("%d | %s\n", i, tokens[i].c_str());
runNum = atoi(tokens[token_size-5].c_str());
sn = atoi(tokens[token_size-4].c_str());
tick2ns = atoi(tokens[token_size-2].c_str());
order = atoi(tokens[token_size-1].c_str());
DPPType = 0;
if( fileName.find("PHA") != std::string::npos ) DPPType = DPPTypeCode::DPP_PHA_CODE;
if( fileName.find("PSD") != std::string::npos ) DPPType = DPPTypeCode::DPP_PSD_CODE;
if( fileName.find("QDC") != std::string::npos ) DPPType = DPPTypeCode::DPP_QDC_CODE;
if( fileName.find("PHA") != std::string::npos ) { printf("Using PHA decode.\n"); DPPType = DPPTypeCode::DPP_PHA_CODE;}
if( fileName.find("PSD") != std::string::npos ) { printf("Using PSD decode.\n"); DPPType = DPPTypeCode::DPP_PSD_CODE;}
if( fileName.find("QDC") != std::string::npos ) { printf("Using QDC decode.\n"); DPPType = DPPTypeCode::DPP_QDC_CODE;}
if( DPPType == 0 ){
fclose(inFile);
inFile = nullptr;
@ -277,11 +291,12 @@ inline void FSUReader::OpenFile(std::string fileName, uInt dataSize, int verbose
}
//^==============================================================
inline int FSUReader::ReadNextBlock(bool traceON, int verbose, uShort saveData){
if( inFile == NULL ) return -1;
if( feof(inFile) || filePos >= inFileSize) {
if( fileID >= 0 && fileID + 1 < (short) fileList.size() ){
printf("-------------- next file\n");
printf("-------------- next file | hit size : %zu\n", hit.size());
fileID ++;
OpenFile(fileList[fileID], data->GetDataSize(), 1 );
}else{
@ -332,13 +347,22 @@ inline int FSUReader::ReadNextBlock(bool traceON, int verbose, uShort saveData){
return -20;
}
unsigned int eventCout = 0;
for( int ch = 0; ch < data->GetNChannel(); ch++){
if( data->NumEventsDecoded[ch] == 0 ) continue;
hitCount += data->NumEventsDecoded[ch];
eventCout += data->NumEventsDecoded[ch];
totalHitCount += data->NumEventsDecoded[ch];
if( totalHitCount / DEFAULT_HALFBUFFERSIZE > nMillion ) {
nMillion ++;
tmin.push_back(-1);
}
int start = data->GetDataIndex(ch) - data->NumEventsDecoded[ch] + 1;
if( start < 0 ) start = start + data->GetDataSize();
for( int i = start; i < start + data->NumEventsDecoded[ch]; i++ ){
int k = i % data->GetDataSize();
if( data->GetTimestamp(ch, k) < tmin[nMillion] ) tmin[nMillion] = data->GetTimestamp(ch, k);
}
if( saveData ){
int start = data->GetDataIndex(ch) - data->NumEventsDecoded[ch] + 1;
@ -346,12 +370,16 @@ inline int FSUReader::ReadNextBlock(bool traceON, int verbose, uShort saveData){
for( int i = start; i < start + data->NumEventsDecoded[ch]; i++ ){
int k = i % data->GetDataSize();
temp.sn = sn;
temp.ch = ch;
temp.energy = data->GetEnergy(ch, k);
temp.energy2 = data->GetEnergy2(ch, k);
temp.timestamp = data->GetTimestamp(ch, k);
// unsigned long long offset = 1000000;
// if( sn == 405 && ch == 0) temp.timestamp -= offset;
temp.fineTime = data->GetFineTime(ch, k);
temp.pileUp = data->GetPileUp(ch, k);
if( saveData > 1 ) {
@ -362,6 +390,8 @@ inline int FSUReader::ReadNextBlock(bool traceON, int verbose, uShort saveData){
if( temp.trace.size() > 0 ) temp.trace.clear();
}
// temp.Print();
hit.push_back(temp);
}
}
@ -373,6 +403,7 @@ inline int FSUReader::ReadNextBlock(bool traceON, int verbose, uShort saveData){
return 0;
}
//^==============================================================
inline int FSUReader::ReadBlock(unsigned int ID, int verbose){
if( totNumBlock == 0 )return -1;
if( ID >= totNumBlock )return -1;
@ -390,6 +421,7 @@ inline int FSUReader::ReadBlock(unsigned int ID, int verbose){
}
//^==============================================================
inline void FSUReader::SortHit(int verbose){
if( verbose) printf("\nQuick Sort hit array according to time...");
std::sort(hit.begin(), hit.end(), [](const Hit& a, const Hit& b) {
@ -398,6 +430,7 @@ inline void FSUReader::SortHit(int verbose){
if( verbose) printf(".......done.\n");
}
//^==============================================================
inline void FSUReader::ScanNumBlock(int verbose, uShort saveData){
if( inFile == nullptr ) return;
if( feof(inFile) ) return;
@ -421,8 +454,8 @@ inline void FSUReader::ScanNumBlock(int verbose, uShort saveData){
totNumBlock = blockID;
if(verbose) {
printf("\nScan complete: number of data Block : %lu\n", totNumBlock);
printf( " number of hit : %lu", hitCount);
if( hitCount > 1e6 ) printf(" = %.3f million", hitCount/1e6);
printf( " number of hit : %lu", totalHitCount);
if( totalHitCount > 1e6 ) printf(" = %.3f million", totalHitCount/1e6);
printf("\n");
if( saveData )printf( " size of the hit array : %lu\n", hit.size());
@ -443,15 +476,33 @@ inline void FSUReader::ScanNumBlock(int verbose, uShort saveData){
//check is the hitCount == hit.size();
if( saveData ){
if( hitCount != hit.size()){
if( totalHitCount != hit.size()){
printf("!!!!!! the Data::dataSize is not big enough. !!!!!!!!!!!!!!!\n");
}else{
SortHit(verbose+1);
}
}
//print time structre
if( nMillion > 0 ){
// printf("------------ time structure\n");
// printf("%5s | %15s\n", "mil.", "t-min");
for( int i = 0; i < nMillion; i++){
// printf("%5d | %15lu", i, tmin[i]);
if( i > 0 && tmin[i] < tmin[i-1] ) {
// printf("<----");
if( i > 1 && tmin[i] < tmin[i-2]) optBufferSize += 2*DEFAULT_HALFBUFFERSIZE;
}
// printf("\n");
}
}
// printf(" recommanded batch size : %lu\n", optBufferSize);
}
inline std::vector<Hit> FSUReader::ReadBatch(unsigned int batchSize, bool verbose){
//^==============================================================
inline std::vector<Hit> FSUReader::ReadBatch(unsigned int batchSize, bool traceOn, bool verbose){
// printf("%s sn:%d. filePos : %lu\n", __func__, sn, ftell(inFile));
@ -465,15 +516,16 @@ inline std::vector<Hit> FSUReader::ReadBatch(unsigned int batchSize, bool verbos
if( hit.size() == 0 ){
int res = 0;
do{
res = ReadNextBlock(true, 0, 3);
res = ReadNextBlock(traceOn, 0, 3);
}while ( hit.size() < batchSize && res == 0);
SortHit();
uLong t0_B = hit.at(0).timestamp;
uLong t1_B = hit.back().timestamp;
if( verbose ) {
printf(" hit in memeory : %7zu | %u | %lu \n", hit.size(), filePos, inFileSize);
printf("t0 : %15lu\n", t0_B);
printf("t1 : %15lu\n", t1_B);
printf("t0 : %15lu ns\n", t0_B);
printf("t1 : %15lu ns\n", t1_B);
printf("dt : %15.3f ms\n", (t1_B - t0_B)/1e6);
}
hitList_A = hit;
@ -490,7 +542,7 @@ inline std::vector<Hit> FSUReader::ReadBatch(unsigned int batchSize, bool verbos
int res = 0;
do{
res = ReadNextBlock(true, 0, 3);
res = ReadNextBlock(traceOn, 0, 3);
}while ( hit.size() < batchSize && res == 0);
SortHit();
uLong t0_B = hit.at(0).timestamp;
@ -500,6 +552,7 @@ inline std::vector<Hit> FSUReader::ReadBatch(unsigned int batchSize, bool verbos
printf(" hit in memeory : %7zu | %u | %lu \n", hit.size(), filePos, inFileSize);
printf("t0 : %15lu\n", t0_B);
printf("t1 : %15lu\n", t1_B);
printf("dt : %15.3f ms\n", (t1_B - t0_B)/1e6);
}
uLong t0_A = hitList_A.at(0).timestamp;
@ -509,6 +562,8 @@ inline std::vector<Hit> FSUReader::ReadBatch(unsigned int batchSize, bool verbos
if( t0_A >= t0_B) {
printf("\033[0;31m!!!!!!!!!!!!!!!!! %s | Need to increase the batch size. \033[0m\n", __func__);
printf("t0_A : %15lu\n", t0_A);
printf("t0_B : %15lu\n", t0_B);
return std::vector<Hit> ();
}
@ -552,8 +607,8 @@ inline std::vector<Hit> FSUReader::ReadBatch(unsigned int batchSize, bool verbos
if( verbose ) {
printf("----------------- ID_A : %lu, Drop\n", ID_A);
printf("----------------- ID_B : %lu, Drop\n", ID_B);
PrintHitListInfo(hitList_A, "hitList_A");
PrintHitListInfo(hitTemp, "hitTemp");
PrintHitListInfo(&hitList_A, "hitList_A");
PrintHitListInfo(&hitTemp, "hitTemp");
PrintHitListInfo();
printf("=========== sume of A + B + Temp : %zu \n", hitList_A.size() + hit.size() + hitTemp.size());
printf("----------------- refill hitList_A \n");
@ -565,7 +620,7 @@ inline std::vector<Hit> FSUReader::ReadBatch(unsigned int batchSize, bool verbos
hitTemp.clear();
if( verbose ) {
PrintHitListInfo(hitList_A, "hitList_A");
PrintHitListInfo(&hitList_A, "hitList_A");
PrintHitListInfo();
printf("=========== sume of A + B : %zu \n", hitList_A.size() + hit.size());
}
@ -576,216 +631,3 @@ inline std::vector<Hit> FSUReader::ReadBatch(unsigned int batchSize, bool verbos
}
/*
inline void FSUReader::SortAndSaveTS(unsigned int batchSize, bool verbose){
int count = 0;
std::vector<Hit> hitList_A ;
do{
if( verbose ) printf("***************************************************\n");
int res = 0;
do{
res = ReadNextBlock(true, 0, 3);
}while ( hit.size() < batchSize && res == 0);
SortHit();
uLong t0_B = hit.at(0).timestamp;
uLong t1_B = hit.back().timestamp;
if( verbose ) {
printf(" hit in memeory : %7zu | %u | %lu \n", hit.size(), filePos, inFileSize);
printf("t0 : %15lu\n", t0_B);
printf("t1 : %15lu\n", t1_B);
}
if( count == 0 ) {
hitList_A = hit; // copy hit
}else{
uLong t0_A = hitList_A.at(0).timestamp;
uLong t1_A = hitList_A.back().timestamp;
ulong ID_A = 0;
ulong ID_B = 0;
if( t0_A > t0_B) {
printf("Need to increase the batch size. \n");
return;
}
if( t1_A > t0_B) { // need to sort between two hitList
if( verbose ) {
printf("############# need to sort \n");
printf("=========== sume of A + B : %zu \n", hitList_A.size() + hit.size());
}
std::vector<Hit> hitTemp;
for( size_t j = 0; j < hitList_A.size() ; j++){
if( hitList_A[j].timestamp < t0_B ) continue;
if( ID_A == 0 ) ID_A = j;
hitTemp.push_back(hitList_A[j]);
}
hitList_A.erase(hitList_A.begin() + ID_A, hitList_A.end() );
if( verbose ) {
printf("----------------- ID_A : %lu, Drop\n", ID_A);
PrintHitListInfo(hitList_A, "hitList_A");
}
for( size_t j = 0; j < hit.size(); j++){
if( hit[j].timestamp > t1_A ) {
ID_B = j;
break;
}
hitTemp.push_back(hit[j]);
}
std::sort(hitTemp.begin(), hitTemp.end(), [](const Hit& a, const Hit& b) {
return a.timestamp < b.timestamp;
});
hit.erase(hit.begin(), hit.begin() + ID_B );
if( verbose ) {
PrintHitListInfo(hitTemp, "hitTemp");
printf("----------------- ID_B : %lu, Drop\n", ID_B);
PrintHitListInfo(hit, "hit");
printf("=========== sume of A + B + Temp : %zu \n", hitList_A.size() + hit.size() + hitTemp.size());
printf("----------------- refill hitList_A \n");
}
ulong ID_Temp = 0;
for( size_t j = 0; j < hitTemp.size(); j++){
hitList_A.push_back(hitTemp[j]);
if( hitList_A.size() >= batchSize ) {
ID_Temp = j+1;
break;
}
}
hitTemp.erase(hitTemp.begin(), hitTemp.begin() + ID_Temp );
for( size_t j = 0 ; j < hit.size(); j ++){
hitTemp.push_back(hit[j]);
}
SaveHit(hitList_A, count <= 1 ? false : true);
if( verbose ) {
PrintHitListInfo(hitList_A, "hitList_A");
PrintHitListInfo(hitTemp, "hitTemp");
printf("----------------- replace hitList_A by hitTemp \n");
}
hitList_A.clear();
hitList_A = hitTemp;
hit.clear();
if( verbose ) {
PrintHitListInfo(hitList_A, "hitList_A");
printf("===========================================\n");
}
}else{ // save hitList_A, replace hitList_A
SaveHit(hitList_A, count <= 1? false : true);
hitList_A.clear();
hitList_A = hit;
if( verbose ) PrintHitListInfo(hitList_A, "hitList_A");
}
}
ClearHitList();
count ++;
}while(filePos < inFileSize);
SaveHit(hitList_A, count <= 1 ? false : true);
printf("================= finished.\n");
}
*/
/*
inline std::string FSUReader::SaveHit(std::vector<Hit> hitList, bool isAppend){
std::string outFileName;
if( fileList.empty() ) {
outFileName = fileName + ".ts" ;
}else{
outFileName = fileList[0] + ".ts" ;
}
uint64_t hitSize = hitList.size();
FILE * outFile ;
if( isAppend ) {
outFile = fopen(outFileName.c_str(), "rb+"); //read/write bineary
rewind(outFile);
fseek( outFile, 4, SEEK_CUR);
uint64_t org_hitSize;
fread(&org_hitSize, 8, 1, outFile);
rewind(outFile);
fseek( outFile, 4, SEEK_CUR);
org_hitSize += hitSize;
fwrite(&org_hitSize, 8, 1, outFile);
fseek(outFile, 0, SEEK_END);
}else{
outFile = fopen(outFileName.c_str(), "wb"); //overwrite binary
uint32_t header = 0xAA000000;
header += sn;
fwrite( &header, 4, 1, outFile );
fwrite( &hitSize, 8, 1, outFile);
}
for( ulong i = 0; i < hitSize; i++){
if( i% 10000 == 0 ) printf("Saving %lu/%lu Hit (%.2f%%)\n\033[A\r", i, hitSize, i*100./hitSize);
uint16_t flag = hitList[i].ch + (hitList[i].pileUp << 8) ;
if( DPPType == DPPTypeCode::DPP_PSD_CODE ) flag += ( 1 << 15);
if( hitList[i].traceLength > 0 ) flag += (1 << 14);
// fwrite( &(hit[i].ch), 1, 1, outFile);
fwrite( &flag, 2, 1, outFile);
fwrite( &(hitList[i].energy), 2, 1, outFile);
if( DPPType == DPPTypeCode::DPP_PSD_CODE ) fwrite( &(hitList[i].energy2), 2, 1, outFile);
fwrite( &(hitList[i].timestamp), 6, 1, outFile);
fwrite( &(hitList[i].fineTime), 2, 1, outFile);
if( hitList[i].traceLength > 0 ) fwrite( &(hitList[i].traceLength), 2, 1, outFile);
for( uShort j = 0; j < hitList[i].traceLength; j++){
fwrite( &(hitList[i].trace[j]), 2, 1, outFile);
}
}
off_t tsFileSize = ftello(outFile); // unsigned int = Max ~4GB
fclose(outFile);
printf("Saved to %s, size: ", outFileName.c_str());
if( tsFileSize < 1024 ) {
printf(" %ld Byte", tsFileSize);
}else if( tsFileSize < 1024*1024 ) {
printf(" %.2f kB", tsFileSize/1024.);
}else if( tsFileSize < 1024*1024*1024){
printf(" %.2f MB", tsFileSize/1024./1024.);
}else{
printf(" %.2f GB", tsFileSize/1024./1024./1024.);
}
printf("\n");
return outFileName;
}
*/

View File

@ -81,7 +81,7 @@ int main(int argc, char **argv) {
tempInfo.fileName = inFileName[i];
tempInfo.readerID = i;
tempInfo.SN = reader[i]->GetSN();
tempInfo.hitCount = reader[i]->GetHitCount();
tempInfo.hitCount = reader[i]->GetTotalHitCount();
tempInfo.fileSize = reader[i]->GetFileByteSize();
tempInfo.tick2ns = reader[i]->GetTick2ns();
tempInfo.DPPType = reader[i]->GetDPPType();
@ -208,7 +208,7 @@ int main(int argc, char **argv) {
}else{
group[gpID].hitID = 0;
uShort rID = group[gpID].readerIDList[group[gpID].currentID];
group[gpID].hitCount = reader[rID]->GetHitCount();
group[gpID].hitCount = reader[rID]->GetTotalHitCount();
printf("-----> go to the next file, %s \n", fileInfo[rID].fileName.c_str() );
}
}

View File

@ -110,7 +110,7 @@ int main(int argc, char **argv) {
tempInfo.fileName = outFileName;
tempInfo.readerID = i;
tempInfo.SN = reader[i]->GetSN();
tempInfo.hitCount = reader[i]->GetHitCount();
tempInfo.hitCount = reader[i]->GetTotalHitCount();
tempInfo.fileSize = reader[i]->GetTSFileSize();
tempInfo.tick2ns = reader[i]->GetTick2ns();
tempInfo.DPPType = reader[i]->GetDPPType();

View File

@ -1,90 +1,114 @@
#include "fsuReader.h"
#include "../MultiBuilder.cpp"
// #include "../MultiBuilder.cpp"
#include "SplitPolePlotter.C"
#include "SplitPolePlotter_MT.C"
void script(){
FSUReader * reader = new FSUReader("~/ExpData/testing/.fsu", 16);
Data * data = reader->GetData();
data->tick2ns = 4;
TChain * chain = new TChain("tree");
// chain->Add("raw_binary/run_13/run013_3000.root");
// chain->Add("data/run*_3000.root");
chain->Add("data/12C_dp_*_3000.root");
reader->ScanNumBlock();
// TFile * pidCutFile = new TFile("cut_proton.root");
TFile * pidCutFile = new TFile("cut_proton_FSU.root");
TCutG * pidCut = (TCutG *) pidCutFile->Get("protons");
// SplitPolePlotter(chain, pidCut, 123.307, 2.75, false); // for CoMPASS data
// SplitPolePlotter(chain, pidCut, 123.307, 2.75, true); // faster then MT?
// for( int i = 0; i < 500 ; i++ ) reader->ReadNextBlock(0, 0);
// int ch = 5;
// std::vector<unsigned long long > tList;
// int nEvent = 0;
// for( int i = 0; i < data->TotNumNonPileUpEvents[ch]; i++){
// tList.push_back(data->Timestamp[ch][i]);
// printf("%3d | %d %llu \n", i, data->Energy[ch][i], data->Timestamp[ch][i]);
// nEvent ++;
// }
// std::sort(tList.begin(), tList.end());
// unsigned long long dTime = tList.back() - tList.front();
// double sec = dTime * data->tick2ns / 1e9;
// printf("=========== %llu, %llu = %llu | %f sec | %f Hz\n", tList.back(), tList.front(), dTime, sec, nEvent/sec );
//data->PrintStat(0);
SplotPolePlotter_MT(chain, 5, pidCut, 123.307, 2.75, true);
data->ClearData();
data->ClearTriggerRate();
//^=====================================================
// FSUReader * reader = new FSUReader("data/12C_dp_002_19555_PSD_4_000.fsu", 10000, 2);
// reader->ScanNumBlock(1, 0);
// reader->ReadNextBlock(0, 9);
// for( int i = 0; i < 10 ; i++ ) reader->ReadNextBlock(0, 9);
// std::vector<Hit> hitList = reader->ReadBatch(10, true);
// for ( int i = 0; i < 10 ; i ++) hitList[i].Print();
// // int ch = 5;
// // std::vector<unsigned long long > tList;
// // int nEvent = 0;
// // for( int i = 0; i < data->TotNumNonPileUpEvents[ch]; i++){
// // tList.push_back(data->Timestamp[ch][i]);
// // printf("%3d | %d %llu \n", i, data->Energy[ch][i], data->Timestamp[ch][i]);
// // nEvent ++;
// // }
// // std::sort(tList.begin(), tList.end());
// // unsigned long long dTime = tList.back() - tList.front();
// // double sec = dTime * data->tick2ns / 1e9;
// // printf("=========== %llu, %llu = %llu | %f sec | %f Hz\n", tList.back(), tList.front(), dTime, sec, nEvent/sec );
// //data->PrintStat(0);
MultiBuilder * mb = new MultiBuilder(data, reader->GetDPPType(), 334);
mb->SetTimeWindow(10000);
unsigned long totNumBlock = reader->GetTotNumBlock();
int lastDataIndex = 0;
int lastLoopIndex = 0;
for( unsigned long i = 0; i < 2; i++){
reader->ReadNextBlock();
// int maxDataIndex = 0;
// int maxLoopIndex = 0;
// for( int ch = 0; ch < 16 ; ch++){
// if( data->DataIndex[ch] > maxDataIndex ) maxDataIndex = data->DataIndex[ch];
// if( data->LoopIndex[ch] > maxLoopIndex ) maxLoopIndex = data->LoopIndex[ch];
// }
// if( (maxLoopIndex * MaxNData + maxDataIndex) - (lastLoopIndex * MaxNData + lastDataIndex) > MaxNData * 0.05){
// printf("Agg ID : %lu \n", i );
// data->PrintStat();
// data->PrintAllData();
// mb->BuildEvents();
// mb->PrintAllEvent();
// mb->PrintStat();
// lastDataIndex = maxDataIndex;
// lastLoopIndex = maxLoopIndex;
// }
}
// data->ClearData();
// data->ClearTriggerRate();
data->PrintStat();
data->PrintAllData();
//mb->BuildEvents(true);
// MultiBuilder * mb = new MultiBuilder(data, reader->GetDPPType(), 334);
// mb->SetTimeWindow(10000);
// unsigned long totNumBlock = reader->GetTotNumBlock();
// int lastDataIndex = 0;
// int lastLoopIndex = 0;
mb->BuildEventsBackWard(300);
// for( unsigned long i = 0; i < 2; i++){
mb->PrintAllEvent();
mb->PrintStat();
// reader->ReadNextBlock();
// // int maxDataIndex = 0;
// // int maxLoopIndex = 0;
// // for( int ch = 0; ch < 16 ; ch++){
// // if( data->DataIndex[ch] > maxDataIndex ) maxDataIndex = data->DataIndex[ch];
// // if( data->LoopIndex[ch] > maxLoopIndex ) maxLoopIndex = data->LoopIndex[ch];
// // }
// // if( (maxLoopIndex * MaxNData + maxDataIndex) - (lastLoopIndex * MaxNData + lastDataIndex) > MaxNData * 0.05){
// // printf("Agg ID : %lu \n", i );
// // data->PrintStat();
// // data->PrintAllData();
// // mb->BuildEvents();
// // mb->PrintAllEvent();
// // mb->PrintStat();
// // lastDataIndex = maxDataIndex;
// // lastLoopIndex = maxLoopIndex;
// // }
// }
delete mb;
delete reader;
// data->PrintStat();
// data->PrintAllData();
// //mb->BuildEvents(true);
}
// mb->BuildEventsBackWard(300);
// mb->PrintAllEvent();
// mb->PrintStat();
// delete mb;
// delete reader;
}

View File

@ -3,6 +3,7 @@
#include "../ClassDigitizer.h"
#include "../MultiBuilder.h"
#include "../ClassInfluxDB.h"
#include "ClassDigitizerAPI.h"
#include <TROOT.h>
#include <TSystem.h>
@ -321,82 +322,121 @@ int TestDigitizerRaw(){
}
//^======================================
int main(int argc, char* argv[]){
TestDigitizerRaw();
// CheckBufferSize(5, 4);
void SimpleDAQ(){
//GetOneAgg();
std::unique_ptr<Digitizer> digi = std::make_unique<Digitizer>(0, 49093, false, true);
digi->ProgramBoard();
digi->SetBits(DPP::QDC::DPPAlgorithmControl, DPP::QDC::Bit_DPPAlgorithmControl::Polarity, 0, -1);
digi->WriteRegister(DPP::QDC::NumberEventsPerAggregate, 5);
digi->SetBits(DPP::BoardConfiguration, DPP::Bit_BoardConfig::RecordTrace, 1, -1); // enable trace recording
digi->WriteRegister(DPP::MaxAggregatePerBlockTransfer, 10);
// digi->WriteRegister(DPP::QDC::PreTrigger, 60, -1);
// digi->WriteRegister(DPP::QDC::TriggerThreshold_sub2, 17, -1);
// digi->SetBits(DPP::QDC::DPPAlgorithmControl, DPP::QDC::Bit_DPPAlgorithmControl::ChargeSensitivity, 0, -1);
// digi->SetBits(DPP::QDC::DPPAlgorithmControl, DPP::QDC::Bit_DPPAlgorithmControl::InputSmoothingFactor, 4, -1);
// digi->SetBits(DPP::QDC::DPPAlgorithmControl, DPP::QDC::Bit_DPPAlgorithmControl::BaselineAvg, 2, -1);
// digi->WriteRegister(DPP::QDC::GateWidth, 608/16, -1);
// digi->WriteRegister(DPP::QDC::GroupEnableMask, 0x01);
// digi->WriteRegister(DPP::QDC::NumberEventsPerAggregate, 10, -1);
// digi->WriteRegister(DPP::AggregateOrganization, 0, -1);
// digi->WriteRegister(DPP::MaxAggregatePerBlockTransfer, 100, -1);
// digi->SetBits(DPP::QDC::DPPAlgorithmControl, DPP::QDC::Bit_DPPAlgorithmControl::Polarity, 0, -1);
/*
digi->SetBits(DPP::BoardConfiguration, DPP::Bit_BoardConfig::EnableExtra2, 1, -1);
digi->SetBits(DPP::BoardConfiguration, DPP::Bit_BoardConfig::RecordTrace, 0, -1);
Data * data = digi->GetData();
MultiBuilder * builder = new MultiBuilder(data, DPPType::DPP_PHA_CODE, digi->GetSerialNumber());
builder->SetTimeWindow(100);
//remove("haha_*.fsu");
//data->OpenSaveFile("haha");
Data * data = digi->GetData();
data->OpenSaveFile("haha2");
digi->StartACQ();
for( int i = 0; i < 5; i ++ ){
usleep(1000*1000);
for( int i = 0; i < 10 ; i++ ){
usleep(500*1000);
digi->ReadData();
data->DecodeBuffer(true, 0);
//data->DecodeBuffer(false, 2);
//data->SaveData();
//data->PrintStat();
data->PrintAllData(true);
data->SetDecimationFactor(3);
data->SaveData();
//builder->BuildEvents(false, true, true);
builder->BuildEventsBackWard(20, true);
builder->PrintStat();
// int index = data->NumEventsDecoded[0];
// printf("-------------- %ld \n", data->Waveform1[0][index].size());
data->PrintStat();
}
digi->StopACQ();
//data->CloseSaveFile();
builder->BuildEvents(true, true, true);
}
data->PrintAllData();
builder->PrintAllEvent(); // TODO
*/
void Compare_CAEN_Decoder(){
// digi->CloseDigitizer();
// delete digi;
std::unique_ptr<Digitizer> digi = std::make_unique<Digitizer>(0, 49093, false, true);
Data * data = digi->GetData();
int ret;
int handle = digi->GetHandle();
CAEN_DGTZ_DPP_PSD_Event_t *Events[16]; /// events buffer
uint32_t NumEvents[16];
uint32_t AllocatedSize = 0;
ret |= CAEN_DGTZ_MallocDPPEvents(handle, reinterpret_cast<void**>(&Events), &AllocatedSize) ;
printf("allowcated %d byte for Events\n", AllocatedSize);
printf("======================== start ACQ \n");
digi->StartACQ();
int ch = 0;
for( int i = 0; i < 5; i ++ ){
usleep(1000*1000); // every 1 second
digi->ReadData();
// data->CopyBuffer(cpBuffer, bufferSize);
data->DecodeBuffer(false, 4);
if( data->nByte > 0 ){
ret = (CAEN_DGTZ_ErrorCode) CAEN_DGTZ_GetDPPEvents(handle, data->buffer, data->nByte, reinterpret_cast<void**>(&Events), NumEvents);
if (ret) {
printf("Error when getting events from data %d\n", ret);
continue;
}
printf("============ %u\n", NumEvents[0]);
for( int ev = 0; ev < NumEvents[0]; ev++ ){
printf("-------- ev %d\n", ev);
printf( " Format : 0x%04x\n", Events[ch][ev].Format);
printf( "TimeTag : 0x%08x\n", Events[ch][ev].TimeTag);
printf(" E_short : 0x%04x\n", Events[ch][ev].ChargeShort);
printf(" E_long : 0x%04x\n", (Events[ch][ev].ChargeLong & 0xffff));
printf("Baseline : 0x%04x\n", (Events[ch][ev].Baseline & 0xffff));
printf(" Pur : 0x%04x\n", Events[ch][ev].Pur);
printf(" Extra : 0x%08x\n", Events[ch][ev].Extras);
}
}
}
digi->StopACQ();
printf("======================== ACQ Stopped.\n");
}
//^======================================
int main(int argc, char* argv[]){
// Compare_CAEN_Decoder();
// Data * data = digi->GetData();
SimpleDAQ();
// MultiBuilder * builder = new MultiBuilder(data, DPPType::DPP_PHA_CODE, digi->GetSerialNumber());
// builder->SetTimeWindow(100);
// std::unique_ptr<DigitizerAPI> digi = std::make_unique<DigitizerAPI>(0, 49093, false, true);
return 0;
}
//*********************************
//*********************************

View File

@ -16,9 +16,6 @@
#include "macro.h"
//#define MaxNData 10000 /// store 10k events per channels
#define DefaultDataSize 10000
enum DPPTypeCode{
DPP_PHA_CODE = 0x8B,
DPP_PSD_CODE = 0x88,
@ -55,14 +52,15 @@ class Data{
int GetLoopIndex(unsigned short ch) const {return LoopIndex[ch];}
int GetDataIndex(unsigned short ch) const {return DataIndex[ch];}
long GetAbsDataIndex(unsigned short ch) const {return LoopIndex[ch] * dataSize + DataIndex[ch];}
uShort GetDataSize() const {return dataSize;}
ullong GetTimestamp(unsigned short ch, unsigned int index) const {return Timestamp[ch][index];}
uShort GetFineTime(unsigned short ch, unsigned int index) const {return fineTime[ch][index];}
uShort GetEnergy(unsigned short ch, unsigned int index) const {return Energy[ch][index];}
uShort GetEnergy2(unsigned short ch, unsigned int index) const {return Energy2[ch][index];}
bool GetPileUp(unsigned short ch, unsigned int index) const {return PileUp[ch][index];}
ullong GetTimestamp(unsigned short ch, unsigned int index) const {return Timestamp[ch][index % dataSize];}
uShort GetFineTime(unsigned short ch, unsigned int index) const {return fineTime[ch][index % dataSize];}
uShort GetEnergy(unsigned short ch, unsigned int index) const {return Energy[ch][index % dataSize];}
uShort GetEnergy2(unsigned short ch, unsigned int index) const {return Energy2[ch][index % dataSize];}
bool GetPileUp(unsigned short ch, unsigned int index) const {return PileUp[ch][index % dataSize];}
uInt GetWordIndex() const {return nw;}
@ -90,6 +88,7 @@ class Data{
unsigned short GetNChannel() const {return numInputCh;}
void PrintBuffer();
void CopyBuffer( const char * buffer, const unsigned int size);
void DecodeBuffer(bool fastDecode, int verbose = 0); /// fastDecode will not save waveform
@ -104,7 +103,8 @@ class Data{
//^================= Saving data
bool OpenSaveFile(std::string fileNamePrefix); // return false when fail
std::string GetOutFileName() const {return outFileName;}
void SaveData();
void SetDecimationFactor(unsigned short factor) { decimation = factor; printf("Set Decimation Factor to be %d\n", factor);}
void SaveData();
void CloseSaveFile();
unsigned int GetFileSize() const {return outFileSize;}
uint64_t GetTotalFileSize() const {return FinishedOutFilesSize + outFileSize;}
@ -137,6 +137,8 @@ class Data{
std::vector<bool> tempDigiWaveform3;
std::vector<bool> tempDigiWaveform4;
unsigned short decimation;
FILE * outFile;
uint64_t FinishedOutFilesSize; // sum of files size.
unsigned int outFileIndex;
@ -176,6 +178,8 @@ inline Data::Data(unsigned short numCh, uInt dataSize): numInputCh(numCh){
ClearNumEventsDecoded();
nw = 0;
decimation = 0;
outFileIndex = 0;
outFilePrefix = "";
outFileName = "";
@ -310,7 +314,7 @@ inline void Data::ClearData(){
if( ch >= numInputCh) break;
for( int j = 0; j < dataSize; j++){
Timestamp[ch][j] = 0;
fineTime[ch][j] = 0;
fineTime[ch][j] = -1;
Energy[ch][j] = 0;
Energy2[ch][j] = 0;
Waveform1[ch][j].clear();
@ -330,6 +334,8 @@ inline void Data::ClearData(){
tempDigiWaveform3.clear();
tempDigiWaveform4.clear();
outFileIndex = 0;
ClearNumEventsDecoded();
ClearTriggerRate();
@ -344,7 +350,10 @@ inline void Data::ClearBuffer(){
}
inline void Data::CopyBuffer(const char * buffer, const unsigned int size){
if( this->buffer ) delete this->buffer;
this->buffer = (char*) malloc(size);
std::memcpy(this->buffer, buffer, size);
this->nByte = size;
}
inline void Data::ClearReferenceTime(){
@ -466,10 +475,146 @@ inline void Data::SaveData(){
outFile = fopen(outFileName.c_str(), "wb"); //overwrite binary
}
fwrite(buffer, nByte, 1, outFile);
outFileSize = ftell(outFile);
if( decimation == 0){
fwrite(buffer, nByte, 1, outFile);
}else{
int Deci = pow(2, decimation);
// printf("Decimation Factor : %d | Deci : %d | nByte %d | nWord %d\n", decimation, Deci, nByte, nByte / 4);
const size_t chunkSize = 4;
size_t numChunk = nByte / chunkSize;
uint32_t word = 0;
int bdAggWordCount = 0;
int groupWordCount = 0;
int chWordCount = 0;
int sampleWordCount = 0;
int bdAggSize = 0;
int groupAggSize = 0;
int sampleSize = 0;
int chAggSize = 0;
uint32_t oldHeader1 = 0;
uint32_t oldHeader2 = 0;
uint32_t oldHeader3 = 0;
uint16_t average = 0; // to calculate Decimation average
for( size_t i = 0; i < numChunk; i++ ){
bdAggWordCount ++;
memcpy(&word, buffer + i * chunkSize, chunkSize);
if( bdAggWordCount <= 4) {
if( bdAggWordCount == 1 ) {
bdAggSize = word & 0x0FFFFFFF;
// printf("###################### Bd Agg Size : %d\n", bdAggSize);
}
// fwrite(buffer + i * chunkSize, sizeof(char), chunkSize, outFile);
// fwrite(&word, sizeof(word), 1, outFile);
if( bdAggWordCount == 2 ) oldHeader1 = word;
if( bdAggWordCount == 3 ) oldHeader2 = word;
if( bdAggWordCount == 4 ) oldHeader3 = word;
}else{
groupWordCount ++;
if( groupWordCount == 1 ) {
groupAggSize = word & 0x3FFFFFFF;
// printf("============= Coupled Channel Agg Size : %d \n", groupAggSize);
}
if( groupWordCount == 2 ) {
sampleSize = (word & 0xFFF) * 8;
bool isExtra = ( (word >> 28 ) & 0x1 );
chAggSize = 2 + sampleSize / 2 + isExtra;
uint32_t newSampleSize = sampleSize / Deci;
// uint32_t oldWord = word;
// word = (word & 0xFFFFF000) + (newSampleSize / 8 ); // change the number of sample
// printf("============= Sample Size : %d | Ch Size : %d | old %08X new %08X\n", sampleSize, chAggSize, oldWord, word);
int nEvent = (groupAggSize - 2 ) / chAggSize;
int newGroupAggSize = 2 + nEvent * ( 2 + newSampleSize / 2 + isExtra );
int newBdAggSize = 4 + newGroupAggSize;
//Write board header and Agg header
uint32_t newHeader0 = (0xA << 28) + newBdAggSize;
fwrite(&newHeader0, sizeof(uint32_t), 1, outFile);
fwrite(&oldHeader1, sizeof(uint32_t), 1, outFile);
fwrite(&oldHeader2, sizeof(uint32_t), 1, outFile);
fwrite(&oldHeader3, sizeof(uint32_t), 1, outFile);
uint32_t newAggHeader0 = (0x8 << 28) + newGroupAggSize ; // add decimation factor in the word
uint32_t newAggHeader1 = (word & 0xFFFFF000) + (newSampleSize / 8 ) + (decimation << 12); // add decimation factor in the word
fwrite(&newAggHeader0, sizeof(uint32_t), 1, outFile);
fwrite(&newAggHeader1, sizeof(uint32_t), 1, outFile);
// printf(" New Board Agg Size : %d \n", newBdAggSize);
// printf(" New Group Agg Size : %d \n", newGroupAggSize);
// printf(" nEvent : %d \n", nEvent);
// printf(" New Event Agg Size : %d \n", 2 + sampleSize / Deci / 2 + isExtra);
// printf("%3d | %08X \n", 1, newHeader0);
// printf("%3d | %08X \n", 2, oldHeader1);
// printf("%3d | %08X \n", 3, oldHeader2);
// printf("%3d | %08X \n", 4, oldHeader3);
// printf("%3d | %3d | %08X \n", 5, 1, newAggHeader0);
// printf("%3d | %3d | %08X \n", 6, 2, newAggHeader1);
}
if( groupWordCount > 2 ) {
chWordCount ++;
if( 1 < chWordCount && chWordCount <= chAggSize - 2 ){ // trace
sampleWordCount ++;
uint16_t S0 = word & 0xFFFF;
uint16_t S1 = (word >> 16) & 0xFFFF;
if( decimation == 1 ){
average = S0/2 + S1/2;
// printf("%3d | %3d | %3d | %3d | %08X | %4X \n", bdAggWordCount, groupWordCount, chWordCount, sampleWordCount, word, average);
fwrite(&average, sizeof(average), 1, outFile);
}else{
average += S0/Deci + S1/Deci;
// printf("%3d | %3d | %3d | %3d | %08X | %4X \n", bdAggWordCount, groupWordCount, chWordCount, sampleWordCount, word, average);
if( sampleWordCount % (Deci/2) == 0) {
// fwrite(&S0, sizeof(S0), 1, outFile);
// printf(" --> %4X \n", average);
fwrite(&average, sizeof(average), 1, outFile);
average = 0;
}
}
}else{
// printf("%3d | %3d | %3d | %08X \n", bdAggWordCount, groupWordCount, chWordCount, word);
fwrite(&word, sizeof(word), 1, outFile);
}
}
if( sampleWordCount == sampleSize / 2 ) sampleWordCount = 0;
if( chAggSize == chWordCount) chWordCount = 0;
if( groupWordCount == groupAggSize ) groupWordCount = 0;
}
if( bdAggWordCount == bdAggSize ) bdAggWordCount = 0;
}
}
outFileSize = ftell(outFile);
}
inline void Data::CloseSaveFile(){
if( outFile != nullptr ){
fclose(outFile);
@ -557,12 +702,22 @@ inline void Data::PrintChData(unsigned short ch, unsigned int maxRowDisplay) con
//^#######################################################
//^####################################################### Decode
inline void Data::PrintBuffer(){
if( buffer == NULL || nByte == 0 ) return;
printf("============== Received nByte : %u\n", nByte);
for( unsigned int i = 0; i < nByte/4; i++ ) {
ReadBuffer(i, 2);
printf("\n");
}
}
inline unsigned int Data::ReadBuffer(unsigned int nWord, int verbose){
if( buffer == NULL ) return 0;
unsigned int word = 0;
for( int i = 0 ; i < 4 ; i++) word += ((buffer[i + 4 * nWord] & 0xFF) << 8*i);
if( verbose >= 2) printf("%6d | 0x%08X | ", nWord, word);
// for( int i = 0 ; i < 4 ; i++) word += ((buffer[i + 4 * nWord] & 0xFF) << 8*i);
memcpy(&word, buffer + 4 * nWord, 4); // Copy 4 bytes directly into word
if( verbose >= 2) printf("%6d | 0x%08X |", nWord, word);
return word;
}
@ -685,6 +840,7 @@ inline int Data::DecodePHADualChannelBlock(unsigned int ChannelMask, bool fastDe
bool hasFormatInfo = ((word >> 31) & 0x1);
unsigned int aggSize = ( word & 0x7FFFFFFF ) ;
if( verbose >= 2 ) printf("Dual Channel size : %d \n", aggSize);
unsigned short decimation = (word >> 12) & 0xF ;
unsigned int nSample = 0; /// wave form;
unsigned int nEvents = 0;
unsigned int extra2Option = 0;
@ -725,6 +881,7 @@ inline int Data::DecodePHADualChannelBlock(unsigned int ChannelMask, bool fastDe
}
}
if( hasWaveForm ){
printf("Sample Size : %d | Decimation: %d \n", nSample, decimation);
printf("...... Analog Probe 1 : ");
switch (analogProbe1 ){
case 0 : printf("Input \n"); break;
@ -882,7 +1039,11 @@ inline int Data::DecodePHADualChannelBlock(unsigned int ChannelMask, bool fastDe
Energy[channel][DataIndex[channel]] = energy;
Timestamp[channel][DataIndex[channel]] = timeStamp * tick2ns;
if(extra2Option == 2 ) fineTime[channel][DataIndex[channel]] = (extra2 & 0x03FF );
if(extra2Option == 2 ) {
fineTime[channel][DataIndex[channel]] = (extra2 & 0x03FF ) * tick2ns; // in ps, the tick2ns is a conversion factor
}else{
fineTime[channel][DataIndex[channel]] = -1;
}
PileUp[channel][DataIndex[channel]] = pileUp;
NumEventsDecoded[channel] ++;
@ -931,6 +1092,7 @@ inline int Data::DecodePSDDualChannelBlock(unsigned int ChannelMask, bool fastDe
unsigned int nEvents = 0;
nw = nw + 1; word = ReadBuffer(nw, verbose);
unsigned short decimation = (word >> 12) & 0xF ;
unsigned int nSample = ( word & 0xFFFF ) * 8;
unsigned int digitalProbe1 = ( (word >> 16 ) & 0x7 );
unsigned int digitalProbe2 = ( (word >> 19 ) & 0x7 );
@ -960,6 +1122,7 @@ inline int Data::DecodePSDDualChannelBlock(unsigned int ChannelMask, bool fastDe
}
}
if( hasWaveForm ){
printf("Sample Size : %d | Decimation: %d \n", nSample, decimation);
printf(".... digital Probe 1 : ");
switch(digitalProbe1){
case 0 : printf("Long gate \n"); break;
@ -1085,7 +1248,11 @@ inline int Data::DecodePSDDualChannelBlock(unsigned int ChannelMask, bool fastDe
Energy2[channel][DataIndex[channel]] = Qshort;
Energy[channel][DataIndex[channel]] = Qlong;
Timestamp[channel][DataIndex[channel]] = timeStamp * tick2ns;
if( extraOption == 2 ) fineTime[channel][DataIndex[channel]] = extra & 0x3FF;
if( extraOption == 2 ) {
fineTime[channel][DataIndex[channel]] = (extra & 0x3FF) * tick2ns; //in ps, tick2ns is justa conversion factor
}else{
fineTime[channel][DataIndex[channel]] = -1; //in ps, tick2ns is justa conversion factor
}
NumEventsDecoded[channel] ++;
if( !pileup){
@ -1110,10 +1277,16 @@ inline int Data::DecodePSDDualChannelBlock(unsigned int ChannelMask, bool fastDe
//if( DataIndex[channel] >= dataSize ) ClearData();
//if( verbose >= 2 ) printf("extra : 0x%08x, Qshort : %d, Qlong : %d \n", extra, Qshort, Qlong);
if( verbose == 1 ) printf("ch : %2d, Qshort : %6d, Qlong : %6d, timestamp : %llu\n",
channel, Qshort, Qlong, timeStamp * tick2ns);
if( verbose >= 2 ) printf("Qshort : %6d, Qlong : %6d, timestamp : %llu\n",
Qshort, Qlong, timeStamp * tick2ns);
if( verbose >= 1 ) {
if( extraOption == 0){
printf("Qshort : %6d, Qlong : %6d, timestamp : %llu, baseline : %u\n",
Qshort, Qlong, timeStamp * tick2ns, (extra & 0xFFFF) * 4);
}
if( extraOption == 2){
printf("Qshort : %6d, Qlong : %6d, timestamp : %llu, fineTime : %u\n",
Qshort, Qlong, timeStamp * tick2ns, (extra & 0x3FF) * tick2ns);
}
}
@ -1129,6 +1302,7 @@ inline int Data::DecodePSDDualChannelBlock(unsigned int ChannelMask, bool fastDe
//*=================================================
inline int Data::DecodeQDCGroupedChannelBlock(unsigned int ChannelMask, bool fastDecode, int verbose){
if( verbose ) printf("########## %s \n", __func__);
//nw = nw + 1;
unsigned int word = ReadBuffer(nw, verbose);
@ -1140,7 +1314,8 @@ inline int Data::DecodeQDCGroupedChannelBlock(unsigned int ChannelMask, bool fas
unsigned int nEvents = 0;
nw = nw + 1; word = ReadBuffer(nw, verbose);
unsigned int nSample = ( word & 0xFFFF ) * 8;
unsigned short decimation = (word >> 12) & 0xF ;
unsigned int nSample = ( word & 0xFFF ) * 8;
unsigned int analogProbe = ( (word >> 22 ) & 0x3 );
bool hasWaveForm = ( (word >> 27 ) & 0x1 );
bool hasExtra = ( (word >> 28 ) & 0x1 );
@ -1151,7 +1326,7 @@ inline int Data::DecodeQDCGroupedChannelBlock(unsigned int ChannelMask, bool fas
if( verbose >= 2 ) {
printf("Charge : %d, Time: %d, Wave : %d, Extra: %d\n", hasEnergy, hasTimeStamp, hasWaveForm, hasExtra);
if( hasWaveForm ){
printf(".... analog Probe (%d): ", analogProbe);
printf("Sample Size : %d | Decimation %d .... analog Probe (%d): ", nSample, decimation, analogProbe);
switch(analogProbe){
case 0 : printf("Input\n"); break;
case 1 : printf("Smoothed Input\n"); break;
@ -1203,7 +1378,7 @@ inline int Data::DecodeQDCGroupedChannelBlock(unsigned int ChannelMask, bool fas
if( verbose >= 3 ){
printf("%4d| %5d, %d, %d, %d, %d \n", 2*wi, (word & 0xFFF) , (( word >> 12 ) & 0x1 ), (( word >> 13 ) & 0x1 ), (( word >> 14 ) & 0x1 ), (( word >> 15 ) & 0x1 ));
printf("%-22s", "");
printf("%-21s", "");
printf("%4d| %5d, %d, %d, %d, %d \n", 2*wi+1, (( word >> 16) & 0xFFF), (( word >> 28 ) & 0x1 ), (( word >> 29 ) & 0x1 ), (( word >> 30 ) & 0x1 ), (( word >> 31 ) & 0x1 ));
}
}

View File

@ -142,8 +142,31 @@ int Digitizer::OpenDigitizer(int boardID, int portID, bool program, bool verbose
NCoupledCh = NumRegChannel;
isInputChEqRegCh = false;
ModelType = ModelTypeCode::VME;
tick2ns = 16.0; break; ///ns -> 62.5 MSamples/s
}
tick2ns = 16.0; ///ns -> 62.5 MSamples/s
// std::string ROC = BoardInfo.ROC_FirmwareRel;
// std::size_t pos = ROC.find(" - ");
// std::string versionROCStr = (pos != std::string::npos) ? ROC.substr(0, pos) : "";
// double versionROC = 0.0;
// if (!versionROCStr.empty()) versionROC = std::stod(versionROCStr);
// printf(" QDC ROC version : %.2f \n", versionROC);
std::string AMC = BoardInfo.AMC_FirmwareRel;
std::size_t pos = AMC.find(" - ");
std::string versionAMCStr = (pos != std::string::npos) ? AMC.substr(0, pos) : "";
double versionAMC = 0.0;
if (!versionAMCStr.empty()) versionAMC = std::stod(versionAMCStr);
printf(" QDC AMC version : %.2f \n", versionAMC);
if( versionAMC < 135.17 ){
printf(" QDC AMC version not support OverThreshold Width.\n");
hasOverThresholdWidth = false;
}else{
hasOverThresholdWidth = true;
}
}; break;
default : tick2ns = 4.0; break;
}
@ -183,7 +206,6 @@ int Digitizer::OpenDigitizer(int boardID, int portID, bool program, bool verbose
/// change address 0xEF08 (5 bits), this will reflected in the 2nd word of the Board Agg. header.
ret = CAEN_DGTZ_WriteRegister(handle, DPP::BoardID, (DPPType & 0xF));
//TODO somehow the bdInfo does not work, use DPPType to set it
uint32_t bdInfo = GetSettingFromMemory(DPP::BoardInfo_R);
uint32_t haha = ((bdInfo >> 8 ) & 0xFF);
@ -258,6 +280,7 @@ int Digitizer::OpenDigitizer(int boardID, int portID, bool program, bool verbose
ErrorMsg("end of OpenDigitizer");
softwareDisable = false;
AcqRun = false;
if( isConnected ) isDummy = false;
@ -278,16 +301,18 @@ int Digitizer::CloseDigitizer(){
isConnected = false;
ret = CAEN_DGTZ_SWStopAcquisition(handle);
printf("-------- Closing Digtizer Board : %d Port : %d \n", boardID, portID);
printf(" Model %s with handle %d using %s\n", BoardInfo.ModelName, handle, LinkType == CAEN_DGTZ_USB ? "USB" : "Optical Link");
if( LinkType == CAEN_DGTZ_USB ) printf(" Model %s with handle %d using USB\n", BoardInfo.ModelName, handle);
if( LinkType == CAEN_DGTZ_OpticalLink ) printf(" Model %s with handle %d using Optical Fiber\n", BoardInfo.ModelName, handle);
if( LinkType == CAEN_DGTZ_USB_A4818 ) printf(" Model %s with handle %d using A4818\n", BoardInfo.ModelName, handle);
ret |= CAEN_DGTZ_CloseDigitizer(handle);
return ret;
}
void Digitizer::SetRegChannelMask(uint32_t mask){
DebugPrint("%s", "Digitizer");
if( softwareDisable ) return;
if( AcqRun ) return;
if( !isConnected ) return;
regChannelMask = mask;
ret |= CAEN_DGTZ_SetChannelEnableMask(handle, regChannelMask);
@ -309,6 +334,7 @@ bool Digitizer::GetInputChannelOnOff(unsigned ch) {
void Digitizer::SetRegChannelOnOff(unsigned short ch, bool onOff){
DebugPrint("%s", "Digitizer");
if( softwareDisable ) return;
if( AcqRun ) return;
if( !isConnected ) return;
regChannelMask = ((regChannelMask & ~( 1 << ch) ) | ( onOff << ch)) ;
SetRegChannelMask(regChannelMask);
@ -316,187 +342,190 @@ void Digitizer::SetRegChannelOnOff(unsigned short ch, bool onOff){
void Digitizer::ProgramBoard(){
DebugPrint("%s", "Digitizer");
if( softwareDisable ) return;
if( AcqRun ) return;
if( DPPType == DPPTypeCode::DPP_PHA_CODE ) ProgramBoard_PHA();
if( DPPType == DPPTypeCode::DPP_PSD_CODE ) ProgramBoard_PSD();
if( DPPType == DPPTypeCode::DPP_QDC_CODE ) ProgramBoard_QDC();
}
void Digitizer::ProgramChannel(short chOrGroup){
if( softwareDisable ) return;
if( AcqRun ) return;
if( DPPType == DPPTypeCode::DPP_PHA_CODE ) ProgramChannel_PHA(chOrGroup);
if( DPPType == DPPTypeCode::DPP_PSD_CODE ) ProgramChannel_PSD(chOrGroup);
if( DPPType == DPPTypeCode::DPP_QDC_CODE ) ProgramChannel_QDC(chOrGroup);
}
int Digitizer::ProgramBoard_PHA(){
DebugPrint("%s", "Digitizer");
if( softwareDisable ) return 0;
printf("===== Digitizer::%s\n", __func__);
//ret = CAEN_DGTZ_Reset(handle);
Reset();
ret = CAEN_DGTZ_WriteRegister(handle, DPP::RecordLength_G + 0x7000, 62);
//*========================== Board
/// change address 0xEF08 (5 bits), this will reflected in the 2nd word of the Board Agg. header.
ret = CAEN_DGTZ_WriteRegister(handle, DPP::BoardID, (DPPType & 0xF));
//WriteRegister(DPP::BoardID, (DPPType & 0xF));
//ret = CAEN_DGTZ_WriteRegister(handle, DPP::BoardConfiguration, 0x0F8915); /// has Extra2, dual trace, input and trap-baseline
ret = CAEN_DGTZ_WriteRegister(handle, DPP::BoardConfiguration, 0x0E8915); /// has Extra2, no trace
ret |= CAEN_DGTZ_WriteRegister(handle, DPP::BoardConfiguration, 0x0E8915); /// has Extra2, no trace
//ret = CAEN_DGTZ_WriteRegister(handle, DPP::BoardConfiguration, 0x0D8115); /// diable Extra2
//TODO change to write register
ret = CAEN_DGTZ_SetAcquisitionMode(handle, CAEN_DGTZ_SW_CONTROLLED); /// software command
ret |= CAEN_DGTZ_SetChannelEnableMask(handle, ModelType == ModelTypeCode::VME ? 0xFFFF : 0x00FF);
ret |= CAEN_DGTZ_SetRunSynchronizationMode(handle, CAEN_DGTZ_RUN_SYNC_Disabled);
ret |= CAEN_DGTZ_SetIOLevel(handle, CAEN_DGTZ_IOLevel_NIM);
ret |= CAEN_DGTZ_SetExtTriggerInputMode(handle, CAEN_DGTZ_TRGMODE_ACQ_ONLY);
ret |= CAEN_DGTZ_WriteRegister(handle, (int32_t)(DPP::GlobalTriggerMask), 0x0);
ret |= CAEN_DGTZ_WriteRegister(handle, (int32_t)(DPP::FrontPanelTRGOUTEnableMask), 0x0);
ret = CAEN_DGTZ_SetChannelEnableMask(handle, ModelType == ModelTypeCode::VME ? 0xFFFF : 0x00FF);
//ret = CAEN_DGTZ_SetNumEventsPerAggregate(handle, 0);
ret = CAEN_DGTZ_SetRunSynchronizationMode(handle, CAEN_DGTZ_RUN_SYNC_Disabled);
if( ret != 0 ) { printf("==== set board error.\n"); return 0;}
uint32_t address;
address = DPP::PHA::DecayTime; ret |= CAEN_DGTZ_WriteRegister(handle, address + 0x7000 , 5000 );
address = DPP::PHA::TrapezoidFlatTop; ret |= CAEN_DGTZ_WriteRegister(handle, address + 0x7000 , 0x1A );
address = DPP::PHA::TrapezoidRiseTime; ret |= CAEN_DGTZ_WriteRegister(handle, address + 0x7000 , 6 );
address = DPP::PHA::PeakingTime; ret |= CAEN_DGTZ_WriteRegister(handle, address + 0x7000 , 6 );
address = DPP::PHA::RCCR2SmoothingFactor; ret |= CAEN_DGTZ_WriteRegister(handle, address + 0x7000 , 4 );
address = DPP::PHA::InputRiseTime; ret |= CAEN_DGTZ_WriteRegister(handle, address + 0x7000 , 6 );
address = DPP::PHA::TriggerThreshold; ret |= CAEN_DGTZ_WriteRegister(handle, address + 0x7000 , 1000 );
address = DPP::PHA::PeakHoldOff; ret |= CAEN_DGTZ_WriteRegister(handle, address + 0x7000 , 0x3E );
address = DPP::PHA::TriggerHoldOffWidth; ret |= CAEN_DGTZ_WriteRegister(handle, address + 0x7000 , 0x3E );
address = DPP::PHA::RiseTimeValidationWindow;ret |= CAEN_DGTZ_WriteRegister(handle, address + 0x7000 , 0x0 );
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, 0x0, 0xAAAA);
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, 0x1, 0xAAAA);
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, 0x2, 0xAAAA);
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, 0x3, 0xAAAA);
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, 0x4, 0xAAAA);
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, 0x5, 0xAAAA);
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, 0x6, 0xAAAA);
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, 0x7, 0xAAAA);
if( ModelType == ModelTypeCode::VME ){
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, 0x8, 0xAAAA);
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, 0x9, 0xAAAA);
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, 0xA, 0xAAAA);
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, 0xB, 0xAAAA);
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, 0xC, 0xAAAA);
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, 0xD, 0xAAAA);
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, 0xE, 0xAAAA);
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, 0xF, 0xAAAA);
}
ret |= CAEN_DGTZ_WriteRegister(handle, (uint32_t)(DPP::PreTrigger) + 0x7000 , 32 );
ret |= CAEN_DGTZ_WriteRegister(handle, (uint32_t)(DPP::InputDynamicRange) + 0x7000 , 0x0 );
ret |= CAEN_DGTZ_WriteRegister(handle, (int32_t)(DPP::DPPAlgorithmControl) + 0x7000, 0x030200f);
if( ret != 0 ) { printf("!!!!!!!! set channels error.\n");}
AutoSetDPPEventAggregation();
/// change address 0xEF08 (5 bits), this will reflected in the 2nd word of the Board Agg. header.
ret = CAEN_DGTZ_WriteRegister(handle, DPP::BoardID, (DPPType & 0xF));
//WriteRegister(DPP::BoardID, (DPPType & 0xF));
//*========================== Group
ProgramChannel_PHA(-1);
isSettingFilledinMemeory = false; /// unlock the ReadAllSettingsFromBoard();
usleep(1000*300);
ReadAllSettingsFromBoard();
return ret;
}
int Digitizer::ProgramBoard_PSD(){
if( softwareDisable ) return 0;
int Digitizer::ProgramChannel_PHA(short ch){
DebugPrint("%s", "Digitizer");
printf("===== Digitizer::%s|ch:%d\n", __func__,ch);
uint32_t channel = (ch << 8);
if( ch < 0 ) channel = 0x7000;
uint32_t address = (ch << 8);
address = channel + DPP::RecordLength_G; ret = CAEN_DGTZ_WriteRegister(handle, address, 62);
address = channel + DPP::PHA::DecayTime; ret |= CAEN_DGTZ_WriteRegister(handle, address, 5000 );
address = channel + DPP::PHA::TrapezoidFlatTop; ret |= CAEN_DGTZ_WriteRegister(handle, address, 0x1A );
address = channel + DPP::PHA::TrapezoidRiseTime; ret |= CAEN_DGTZ_WriteRegister(handle, address, 6 );
address = channel + DPP::PHA::PeakingTime; ret |= CAEN_DGTZ_WriteRegister(handle, address, 6 );
address = channel + DPP::PHA::RCCR2SmoothingFactor; ret |= CAEN_DGTZ_WriteRegister(handle, address, 4 );
address = channel + DPP::PHA::InputRiseTime; ret |= CAEN_DGTZ_WriteRegister(handle, address, 6 );
address = channel + DPP::PHA::TriggerThreshold; ret |= CAEN_DGTZ_WriteRegister(handle, address, 1000 );
address = channel + DPP::PHA::PeakHoldOff; ret |= CAEN_DGTZ_WriteRegister(handle, address, 0x3E );
address = channel + DPP::PHA::TriggerHoldOffWidth; ret |= CAEN_DGTZ_WriteRegister(handle, address, 0x3E );
address = channel + DPP::PHA::RiseTimeValidationWindow;ret |= CAEN_DGTZ_WriteRegister(handle, address, 0x0 );
address = channel + DPP::PreTrigger; ret |= CAEN_DGTZ_WriteRegister(handle, address, 32 );
address = channel + DPP::InputDynamicRange; ret |= CAEN_DGTZ_WriteRegister(handle, address, 0x0 );
address = channel + DPP::DPPAlgorithmControl; ret |= CAEN_DGTZ_WriteRegister(handle, address, 0x030200f);
address = channel + DPP::PHA::DPPAlgorithmControl2_G; ret |= CAEN_DGTZ_WriteRegister(handle, address, 0x200); // use fine time
if( ch >= 0 ) {
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, ch, 0xAAAA);
}else{
for( int i = 0; i < NumRegChannel; i ++ ){
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, i, 0xAAAA);
}
}
if( ret != 0 ) { printf("!!!!!!!! set channels error.\n");}
AutoSetDPPEventAggregation();
if( ch >= 0 ){
isSettingFilledinMemeory = false;
usleep(1000*300);
ReadAllSettingsFromBoard();
}
return ret;
}
int Digitizer::ProgramBoard_PSD(){
DebugPrint("%s", "Digitizer");
printf("===== Digitizer::%s\n", __func__);
//ret = CAEN_DGTZ_Reset(handle);
Reset();
//ret = CAEN_DGTZ_WriteRegister(handle, DPP::BoardConfiguration, 0x0F0115); /// has Extra2, dual trace, input and CFD
ret = CAEN_DGTZ_WriteRegister(handle, DPP::BoardConfiguration, 0x0E0115); /// has Extra2, no trace
ret = CAEN_DGTZ_SetAcquisitionMode(handle, CAEN_DGTZ_SW_CONTROLLED); /// software command
ret |= CAEN_DGTZ_SetIOLevel(handle, CAEN_DGTZ_IOLevel_NIM);
ret |= CAEN_DGTZ_SetExtTriggerInputMode(handle, CAEN_DGTZ_TRGMODE_ACQ_ONLY);
ret |= CAEN_DGTZ_SetChannelEnableMask(handle, 0xFFFF);
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, 0x0, 0xAAAA);
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, 0x1, 0xAAAA);
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, 0x2, 0xAAAA);
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, 0x3, 0xAAAA);
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, 0x4, 0xAAAA);
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, 0x5, 0xAAAA);
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, 0x6, 0xAAAA);
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, 0x7, 0xAAAA);
if( ModelType == ModelTypeCode::VME ){
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, 0x8, 0xAAAA);
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, 0x9, 0xAAAA);
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, 0xA, 0xAAAA);
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, 0xB, 0xAAAA);
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, 0xC, 0xAAAA);
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, 0xD, 0xAAAA);
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, 0xE, 0xAAAA);
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, 0xF, 0xAAAA);
}
ret |= CAEN_DGTZ_WriteRegister(handle, (uint32_t)(DPP::PreTrigger) + 0x7000 , 20 );
ret |= CAEN_DGTZ_WriteRegister(handle, (uint32_t)(DPP::RecordLength_G) + 0x7000 , 80 );
ret |= CAEN_DGTZ_WriteRegister(handle, (uint32_t)(DPP::PSD::ShortGateWidth) + 0x7000 , 32 );
ret |= CAEN_DGTZ_WriteRegister(handle, (uint32_t)(DPP::PSD::LongGateWidth) + 0x7000 , 64 );
ret |= CAEN_DGTZ_WriteRegister(handle, (uint32_t)(DPP::PSD::GateOffset) + 0x7000 , 19 );
if( ret != 0 ) { printf("!!!!!!!! set channels error.\n");}
//*========================== Board
/// change address 0xEF08 (5 bits), this will reflected in the 2nd word of the Board Agg. header.
ret = CAEN_DGTZ_WriteRegister(handle, DPP::BoardID, (DPPType & 0xF));
//WriteRegister(DPP::BoardID, (DPPType & 0xF));
AutoSetDPPEventAggregation();
//ret = CAEN_DGTZ_WriteRegister(handle, DPP::BoardConfiguration, 0x0F0115); /// has Extra2, dual trace, input and CFD
ret |= CAEN_DGTZ_WriteRegister(handle, DPP::BoardConfiguration, 0x0E0115); /// has Extra2, no trace
ret |= CAEN_DGTZ_SetAcquisitionMode(handle, CAEN_DGTZ_SW_CONTROLLED); /// software command
ret |= CAEN_DGTZ_SetIOLevel(handle, CAEN_DGTZ_IOLevel_NIM);
ret |= CAEN_DGTZ_SetExtTriggerInputMode(handle, CAEN_DGTZ_TRGMODE_ACQ_ONLY);
ret |= CAEN_DGTZ_WriteRegister(handle, (int32_t)(DPP::GlobalTriggerMask), 0x0);
ret |= CAEN_DGTZ_WriteRegister(handle, (int32_t)(DPP::FrontPanelTRGOUTEnableMask), 0x0);
ret |= CAEN_DGTZ_SetChannelEnableMask(handle, 0xFFFF);
//*========================== Group
ProgramChannel_PSD(-1);
isSettingFilledinMemeory = false; /// unlock the ReadAllSettingsFromBoard();
usleep(1000*300);
ReadAllSettingsFromBoard();
return ret;
}
int Digitizer::ProgramChannel_PSD(short ch){
DebugPrint("%s", "Digitizer");
printf("===== Digitizer::%s|ch:%d\n", __func__,ch);
uint32_t channel = (ch << 8);
if( ch < 0 ) channel = 0x7000;
uint32_t address = (ch << 8);
address = channel + DPP::PSD::DPPAlgorithmControl2_G; ret = CAEN_DGTZ_WriteRegister(handle, address, 0x00000200 ); // use fine time
address = channel + DPP::DPPAlgorithmControl; ret |= CAEN_DGTZ_WriteRegister(handle, address, 0x00100003 ); // baseline 16 sample, 320fC
address = channel + DPP::PSD::TriggerThreshold; ret |= CAEN_DGTZ_WriteRegister(handle, address, 100 );
address = channel + DPP::PreTrigger; ret |= CAEN_DGTZ_WriteRegister(handle, address, 20 );
address = channel + DPP::RecordLength_G; ret |= CAEN_DGTZ_WriteRegister(handle, address, 80 );
address = channel + DPP::PSD::ShortGateWidth; ret |= CAEN_DGTZ_WriteRegister(handle, address, 32 );
address = channel + DPP::PSD::LongGateWidth; ret |= CAEN_DGTZ_WriteRegister(handle, address, 64 );
address = channel + DPP::PSD::GateOffset; ret |= CAEN_DGTZ_WriteRegister(handle, address, 19 );
if( ch >= 0 ) {
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, ch, 0xAAAA);
}else{
for( int i = 0; i < NumRegChannel; i ++ ){
ret |= CAEN_DGTZ_SetChannelDCOffset(handle, i, 0xAAAA);
}
}
if( ret != 0 ) { printf("!!!!!!!! set channels error.\n");}
AutoSetDPPEventAggregation();
if( ch >= 0 ){
isSettingFilledinMemeory = false;
usleep(1000*300);
ReadAllSettingsFromBoard();
}
return ret;
}
int Digitizer::ProgramBoard_QDC(){
if( softwareDisable ) return 0;
DebugPrint("%s", "Digitizer");
printf("===== Digitizer::%s\n", __func__);
Reset();
int ret = 0;
//*========================== Board
/// change address 0xEF08 (5 bits), this will reflected in the 2nd word of the Board Agg. header.
ret = CAEN_DGTZ_WriteRegister(handle, DPP::BoardID, (DPPType & 0xF));
//WriteRegister(DPP::BoardID, (DPPType & 0xF));
//WriteRegister(DPP::QDC::NumberEventsPerAggregate, 0x10, -1);
WriteRegister(DPP::QDC::RecordLength_W, 16, -1); // 128 sample = 2048 ns
WriteRegister(DPP::QDC::PreTrigger, 60, -1); // at 60 sample = 960 ns
WriteRegister(DPP::QDC::GateWidth, 100/16, -1);
WriteRegister(DPP::QDC::GateOffset, 0, -1);
WriteRegister(DPP::QDC::FixedBaseline, 0, -1);
//WriteRegister(DPP::QDC::DPPAlgorithmControl, 0x300112); // with test pulse, positive
//WriteRegister(DPP::QDC::DPPAlgorithmControl, 0x300102); // No test pulse, positive
WriteRegister(DPP::QDC::DPPAlgorithmControl, 0x310102); // No test pulse, negative
WriteRegister(DPP::QDC::TriggerHoldOffWidth, 100/16, -1);
WriteRegister(DPP::QDC::TRGOUTWidth, 100/16, -1);
//WriteRegister(DPP::QDC::OverThresholdWidth, 100/16, -1);
WriteRegister(DPP::QDC::SubChannelMask, 0xFF, -1);
WriteRegister(DPP::QDC::DCOffset, 0xAAAA, -1);
WriteRegister(DPP::QDC::TriggerThreshold_sub0, 100, -1);
WriteRegister(DPP::QDC::TriggerThreshold_sub1, 100, -1);
WriteRegister(DPP::QDC::TriggerThreshold_sub2, 100, -1);
WriteRegister(DPP::QDC::TriggerThreshold_sub3, 100, -1);
WriteRegister(DPP::QDC::TriggerThreshold_sub4, 100, -1);
WriteRegister(DPP::QDC::TriggerThreshold_sub5, 100, -1);
WriteRegister(DPP::QDC::TriggerThreshold_sub6, 100, -1);
WriteRegister(DPP::QDC::TriggerThreshold_sub7, 100, -1);
WriteRegister(DPP::BoardConfiguration, 0xE0110);
//WriteRegister(DPP::AggregateOrganization, 0x0);
//WriteRegister(DPP::MaxAggregatePerBlockTransfer, 100);
@ -506,18 +535,55 @@ int Digitizer::ProgramBoard_QDC(){
WriteRegister(DPP::FrontPanelIOControl, 0x0);
WriteRegister(DPP::QDC::GroupEnableMask, 0xFF);
/// change address 0xEF08 (5 bits), this will reflected in the 2nd word of the Board Agg. header.
ret = CAEN_DGTZ_WriteRegister(handle, DPP::BoardID, (DPPType & 0xF));
//WriteRegister(DPP::BoardID, (DPPType & 0xF));
//*========================== Group
ProgramChannel_QDC(-1);
isSettingFilledinMemeory = false; /// unlock the ReadAllSettingsFromBoard();
usleep(1000*300);
ReadAllSettingsFromBoard();
return ret;
}
int Digitizer::ProgramChannel_QDC(short group){
printf("===== Digitizer::%s|ch:%d\n", __func__,group);
WriteRegister(DPP::QDC::PreTrigger, 60, group); // at 60 sample = 960 ns
WriteRegister(DPP::QDC::GateWidth, 100/16, group);
WriteRegister(DPP::QDC::GateOffset, 0, group);
WriteRegister(DPP::QDC::FixedBaseline, 0, group);
//WriteRegister(DPP::QDC::DPPAlgorithmControl, 0x300112); // with test pulse, positive
//WriteRegister(DPP::QDC::DPPAlgorithmControl, 0x300102); // No test pulse, positive
WriteRegister(DPP::QDC::DPPAlgorithmControl, 0x310102); // No test pulse, negative
WriteRegister(DPP::QDC::TriggerHoldOffWidth, 100/16, group);
WriteRegister(DPP::QDC::TRGOUTWidth, 100/16, group);
//WriteRegister(DPP::QDC::OverThresholdWidth, 100/16, group);
WriteRegister(DPP::QDC::SubChannelMask, 0xFF, group);
WriteRegister(DPP::QDC::DCOffset, 0xAAAA, group);
WriteRegister(DPP::QDC::TriggerThreshold_sub0, 100, group);
WriteRegister(DPP::QDC::TriggerThreshold_sub1, 100, group);
WriteRegister(DPP::QDC::TriggerThreshold_sub2, 100, group);
WriteRegister(DPP::QDC::TriggerThreshold_sub3, 100, group);
WriteRegister(DPP::QDC::TriggerThreshold_sub4, 100, group);
WriteRegister(DPP::QDC::TriggerThreshold_sub5, 100, group);
WriteRegister(DPP::QDC::TriggerThreshold_sub6, 100, group);
WriteRegister(DPP::QDC::TriggerThreshold_sub7, 100, group);
AutoSetDPPEventAggregation();
isSettingFilledinMemeory = false; /// unlock the ReadAllSettingsFromBoard();
if( group >= 0 ){
isSettingFilledinMemeory = false;
usleep(1000*300);
ReadAllSettingsFromBoard();
}
usleep(1000*300);
ReadAllSettingsFromBoard();
return ret;
}
//========================================================= ACQ control
@ -568,14 +634,13 @@ void Digitizer::StartACQ(){
}
AcqRun = true;
data->ClearTriggerRate();
data->ClearData();
if( DPPType == DPPTypeCode::DPP_QDC_CODE ) SetOptimialAggOrg();
if( DPPType == DPPTypeCode::DPP_QDC_CODE ) SetQDCOptimialAggOrg();
printf(" ACQ mode : %s (%d), TRG-OUT mode : %s (%d) \n", acqStr.c_str(), acqID, trgOutStr.c_str(), trgOutID);
AcqRun = true;
usleep(1000); // wait for 1 msec to start/Arm ACQ;
ret = CAEN_DGTZ_SWStartAcquisition(handle);
@ -603,6 +668,8 @@ void Digitizer::StopACQ(){
data->ClearBuffer();
data->ClearReferenceTime();
data->ZeroTotalFileSize();
ReadACQStatus();
}
unsigned int Digitizer::CalByteForBuffer(bool verbose){
@ -667,7 +734,7 @@ unsigned int Digitizer::CalByteForBufferCAEN(){
uint32_t AllocatedSize;
ret = CAEN_DGTZ_MallocReadoutBuffer(handle, &BufferCAEN, &AllocatedSize);
delete BufferCAEN;
if( BufferCAEN) delete BufferCAEN;
return AllocatedSize;
}
@ -723,6 +790,7 @@ void Digitizer::ReadAndPrintACQStatue(){
//===========================================================
void Digitizer::WriteRegister (Reg registerAddress, uint32_t value, int ch, bool isSave2MemAndFile){
if( softwareDisable ) return;
if( AcqRun ) return;
printf("WRITE|%30s[0x%04X](digi-%d,ch-%02d) [0x%04X]: 0x%08X \n", registerAddress.GetNameChar(), registerAddress.GetAddress(),GetSerialNumber(), ch, registerAddress.ActualAddress(ch), value);
if( !isConnected ) {
@ -732,9 +800,12 @@ void Digitizer::WriteRegister (Reg registerAddress, uint32_t value, int ch, bool
}
if( registerAddress.GetRWType() == RW::ReadONLY ) return;
if( !hasOverThresholdWidth && registerAddress == DPP::QDC::OverThresholdWidth ) return ;
ret = CAEN_DGTZ_WriteRegister(handle, registerAddress.ActualAddress(ch), value);
if( registerAddress == DPP::DecimationFactor ) data->SetDecimationFactor(value);
if( ret == 0 && isSave2MemAndFile && !AcqRun && registerAddress.GetRWType() == RW::ReadWrite ) {
if( ch < 0 ) {
if( registerAddress.GetAddress() < 0x8000 ){
@ -769,10 +840,13 @@ void Digitizer::WriteRegister (Reg registerAddress, uint32_t value, int ch, bool
uint32_t Digitizer::ReadRegister(Reg registerAddress, unsigned short ch, bool isSave2MemAndFile, std::string str ){
DebugPrint("%s", "Digitizer");
if( softwareDisable ) return 0;
if( AcqRun ) return 0;
if( !isConnected ) return 0;
if( registerAddress.GetRWType() == RW::WriteONLY ) return 0;
// if( registerAddress == DPP::QDC::RecordLength_W ) return 0;
if( !hasOverThresholdWidth && registerAddress == DPP::QDC::OverThresholdWidth ) return 0;
ret = CAEN_DGTZ_ReadRegister(handle, registerAddress.ActualAddress(ch), &returnData);
if( ret == 0 && isSave2MemAndFile && !AcqRun) {
@ -781,6 +855,8 @@ uint32_t Digitizer::ReadRegister(Reg registerAddress, unsigned short ch, bool is
SaveSettingToFile(registerAddress, returnData, ch);
}
if( registerAddress == DPP::DecimationFactor ) data->SetDecimationFactor( returnData );
std::stringstream ss;
ss << std::hex << registerAddress.ActualAddress(ch);
@ -857,8 +933,8 @@ Reg Digitizer::FindRegister(uint32_t address){
void Digitizer::ReadAllSettingsFromBoard(bool force){
if( softwareDisable ) return;
if( !isConnected ) return;
if( AcqRun ) return;
if( !isConnected ) return;
if( isSettingFilledinMemeory && !force) return;
printf("===== Digitizer(%d)::%s \n", GetSerialNumber(), __func__);
@ -917,6 +993,7 @@ void Digitizer::ReadAllSettingsFromBoard(bool force){
void Digitizer::ProgramSettingsToBoard(){
DebugPrint("%s", "Digitizer");
if( softwareDisable ) return;
if( AcqRun ) return;
if( !isConnected || isDummy ) return;
printf("========== %s \n", __func__);
@ -985,6 +1062,8 @@ void Digitizer::ProgramSettingsToBoard(){
haha = DPP::QDC::RecordLength_W; WriteRegister(haha, GetSettingFromMemory(haha), -1, false);
// haha = DPP::QDC::NumberEventsPerAggregate; WriteRegister(haha, GetSettingFromMemory(haha), -1, false);
haha = DPP::DecimationFactor; WriteRegister(haha, GetSettingFromMemory(haha), -1, false);
/// Channels Setting
for( int ch = 0; ch < GetNumRegChannels(); ch ++){
for( int p = 0; p < (int) RegisterChannelList_QDC.size(); p++){
@ -1005,6 +1084,7 @@ void Digitizer::ProgramSettingsToBoard(){
}
void Digitizer::SetSettingToMemory(Reg registerAddress, unsigned int value, unsigned short ch ){
if( AcqRun ) return;
DebugPrint("%s", "Digitizer");
unsigned short index = registerAddress.Index(ch);
if( index > SETTINGSIZE ) return;
@ -1300,6 +1380,7 @@ void Digitizer::ErrorMsg(std::string header){
void Digitizer::SetDPPAlgorithmControl(uint32_t bit, int ch){
DebugPrint("%s", "Digitizer");
if( softwareDisable ) return;
if( AcqRun ) return;
WriteRegister( DPP::DPPAlgorithmControl, bit, ch);
if( ret != 0 ) ErrorMsg(__func__);
}
@ -1307,6 +1388,7 @@ void Digitizer::SetDPPAlgorithmControl(uint32_t bit, int ch){
unsigned int Digitizer::ReadBits(Reg address, unsigned int bitLength, unsigned int bitSmallestPos, int ch ){
DebugPrint("%s", "Digitizer");
if( softwareDisable ) return 0;
if( AcqRun ) return 0;
int tempCh = ch;
if (ch < 0 && address < 0x8000 ) tempCh = 0; /// take ch-0
uint32_t bit = ReadRegister(address, tempCh);
@ -1317,6 +1399,7 @@ unsigned int Digitizer::ReadBits(Reg address, unsigned int bitLength, unsigned i
void Digitizer::SetBits(Reg address, unsigned int bitValue, unsigned int bitLength, unsigned int bitSmallestPos, int ch){
DebugPrint("%s", "Digitizer");
if( softwareDisable ) return;
if( AcqRun ) return;
///printf("address : 0x%X, value : 0x%X, len : %d, pos : %d, ch : %d \n", address, bitValue, bitLength, bitSmallestPos, ch);
uint32_t bit ;
uint32_t bitmask = (uint(pow(2, bitLength)-1) << bitSmallestPos);
@ -1331,7 +1414,50 @@ void Digitizer::SetBits(Reg address, unsigned int bitValue, unsigned int bitLeng
if( ret != 0 ) ErrorMsg(__func__);
}
void Digitizer::SetOptimialAggOrg(){
void Digitizer::AutoSetDPPEventAggregation(){
//ret = CAEN_DGTZ_SetDPPAcquisitionMode(handle, CAEN_DGTZ_DPP_ACQ_MODE_List, CAEN_DGTZ_DPP_SAVE_PARAM_EnergyAndTime);
// if( DPPType == DPPTypeCode::DPP_QDC_CODE ){
// }else{
// for( int ch = 0; ch < GetNumInputCh(); ch += 2 ){
// uint32_t a1, a2;
// ret |= CAEN_DGTZ_GetRecordLength(handle, &a1, ch);
// ret |= CAEN_DGTZ_GetNumEventsPerAggregate(handle, &a2, ch);
// printf("Ch %2d | RecordLength : %d | Event Agg : %d \n", ch, a1, a2);
// }
// uint32_t chMask ;
// ret |= CAEN_DGTZ_GetChannelEnableMask(handle, &chMask);
// printf("Ch Mask %0X \n", chMask);
// }
ret = 0;
ret |= CAEN_DGTZ_SetDPPEventAggregation(handle, 0, 0); // AutoSet
if( ret != 0 ) {
printf("!!!!!!!! set %s error.\n", __func__);
}else{
Reg regAdd = DPP::AggregateOrganization;
uint32_t haha = ReadRegister(regAdd);
SetSettingToMemory(regAdd, haha, 0);
SaveSettingToFile(regAdd, haha, 0);
}
}
uint32_t Digitizer::ReadQDCRecordLength() {
returnData = ReadRegister(DPP::QDC::RecordLength_R);
Reg temp = DPP::QDC::RecordLength_R;
int indexR = temp.Index(0);
temp = DPP::QDC::RecordLength_W;
int indexW = temp.Index(0);
setting[indexW] = setting[indexR];
//printf("%d %d | %u %u \n", indexR, indexW, setting[indexR], setting[indexW]);
return returnData;
}
void Digitizer::SetQDCOptimialAggOrg(){
DebugPrint("%s", "Digitizer");
if( DPPType != DPPTypeCode::DPP_QDC_CODE ) {
printf("%s | this method only support QDC board.\n", __func__);
@ -1353,7 +1479,7 @@ void Digitizer::SetOptimialAggOrg(){
printf("=================================== Setting related to Buffer\n");
printf(" agg. orgainzation (bit) : 0x%X \n", aggOrgan);
printf(" Channel Mask : %04X \n", chMask);
printf(" Channel Mask : %08X \n", chMask);
printf("Max number of Agg per Readout : %u \n", AggRead);
printf(" is Extra enabed : %u \n", Ex );
printf(" is Record wave : %u \n", traceOn );
@ -1361,7 +1487,6 @@ void Digitizer::SetOptimialAggOrg(){
printf(" Record Length (bit) : %u = %u sample = %u ns\n", RecordLen, RecordLen*8, RecordLen*8*16);
printf("==============================================================\n");
int eventSize = 6 + 2 * Ex + traceOn * RecordLen * 8; // sample
printf(" estimated event size : %d sample \n", eventSize);
double maxAggOrg = log2( MemorySizekSample * 1024 / eventSize / EventAgg );

View File

@ -60,6 +60,7 @@ class Digitizer{
bool isSettingFileExist; ///
bool isSettingFileUpdate;
bool isSettingFilledinMemeory; /// false for disabled ReadAllSettingFromBoard()
bool hasOverThresholdWidth; /// for QDC
unsigned int setting[SETTINGSIZE]; /// Setting, 4bytes x 2048 = 8192 bytes
//^-------- other protected functions
@ -73,6 +74,10 @@ class Digitizer{
int ProgramBoard_PSD() ;
int ProgramBoard_QDC() ;
int ProgramChannel_PHA(short ch) ; /// program a default PHA Channel for Si-detector, ch = -1 for all channel
int ProgramChannel_PSD(short ch) ; /// program a default PSD Channel for Si-detector, ch = -1 for all channel
int ProgramChannel_QDC(short group) ; /// program a default QDC group for Si-detector, ch = -1 for all group
public:
Digitizer(); /// no digitizer open
Digitizer(int boardID, int portID = 0, bool program = false, bool verbose = false);
@ -95,12 +100,9 @@ class Digitizer{
void PrintBoard();
void ProgramBoard();
void AutoSetDPPEventAggregation(){
//ret = CAEN_DGTZ_SetDPPAcquisitionMode(handle, CAEN_DGTZ_DPP_ACQ_MODE_List, CAEN_DGTZ_DPP_SAVE_PARAM_EnergyAndTime);
ret |= CAEN_DGTZ_SetNumEventsPerAggregate(handle, 10);
ret |= CAEN_DGTZ_SetDPPEventAggregation(handle, 0, 0); // AutoSet
if( ret != 0 ) { printf("!!!!!!!! set %s error.\n", __func__);}
}
void ProgramChannel(short chOrGroup);
void AutoSetDPPEventAggregation();
//^================ ACQ control
void StopACQ();
@ -151,6 +153,7 @@ class Digitizer{
int GetErrorCode() const {return ret;}
unsigned int GetChMemSizekSample() const {return MemorySizekSample;}
std::string GetFamilyName() const {return familyName;}
bool HasOverThresholdWidth_QDC() const {return hasOverThresholdWidth;}
//^================ Setting
Reg FindRegister(uint32_t address);
@ -192,18 +195,12 @@ class Digitizer{
bool IsDualTrace_PHA() {return ( (GetSettingFromMemory(DPP::BoardConfiguration) >> 11) & 0x1 );}
bool IsRecordTrace() {return ( (GetSettingFromMemory(DPP::BoardConfiguration) >> 16) & 0x1 );}
void SetOptimialAggOrg();
//QDC read recordLength
uint32_t ReadQDCRecordLength() {
returnData = ReadRegister(DPP::QDC::RecordLength_R);
Reg temp = DPP::QDC::RecordLength_R;
int indexR = temp.Index(0);
temp = DPP::QDC::RecordLength_W;
int indexW = temp.Index(0);
setting[indexW] = setting[indexR];
//printf("%d %d | %u %u \n", indexR, indexW, setting[indexR], setting[indexW]);
return returnData;
uint32_t ReadQDCRecordLength();
void SetQDCOptimialAggOrg();
void SetTrace(bool onOff){
SetBits(DPP::BoardConfiguration, DPP::Bit_BoardConfig::RecordTrace, onOff, -1);
}
};

View File

@ -69,7 +69,6 @@ public:
digi->WriteRegister(DPP::SoftwareClear_W, 1);
digi->GetData()->ClearData();
}
digi->ReadACQStatus();
digiMTX[ID].unlock();
emit sendMsg("Digi-" + QString::number(digi->GetSerialNumber()) + " ACQ off.");
stop = true;
@ -119,6 +118,7 @@ public:
waitTime = 20; // multiple of 100 mili sec
stop = false;
}
bool isStopped() const {return stop;}
void Stop() { this->stop = true;}
void SetWaitTimeinSec(float sec) {waitTime = sec * 10 ;}
float GetWaitTimeinSec() const {return waitTime/10.;}

View File

@ -130,7 +130,7 @@ protected:
QAction *selectedAction = menu->exec(event->globalPosition().toPoint());
if( selectedAction == a1 ) {
chart()->zoomReset();
chart()->axes(Qt::Vertical).first()->setRange(-(0x3FFF), 0x3FFF);
// chart()->axes(Qt::Vertical).first()->setRange(-(0x3FFF), 0x3FFF);
}
}
@ -169,7 +169,7 @@ protected:
case Qt::Key_Down: chart()->scroll(0, -10); break;
case Qt::Key_R :
chart()->zoomReset();
chart()->axes(Qt::Vertical).first()->setRange(-(0x3FFF), 0x3FFF);
// chart()->axes(Qt::Vertical).first()->setRange(-(0x3FFF), 0x3FFF);
break;
default: QGraphicsView::keyPressEvent(event); break;
}

View File

@ -7,6 +7,8 @@
#include <QDir>
#include <QFileDialog>
#include <QSortFilterProxyModel>
#include <QApplication>
#include <QScreen>
#define ComBoxMixed "Mixed"
// bit = 0, bit = 1
@ -38,7 +40,16 @@ DigiSettingsPanel::DigiSettingsPanel(Digitizer ** digi, unsigned int nDigi, QStr
enableSignalSlot = false;
setWindowTitle("Digitizer Settings");
setGeometry(0, 0, 1700, 850);
//====== resize window if screen too small
QScreen * screen = QGuiApplication::primaryScreen();
QRect screenGeo = screen->geometry();
if( screenGeo.width() < 1700 || screenGeo.height() < 850) {
setGeometry(0, 0, screenGeo.width() - 100, screenGeo.height() - 100);
}else{
setGeometry(0, 0, 1700, 850);
}
// setGeometry(0, 0, 1700, 850);
tabWidget = new QTabWidget(this);
setCentralWidget(tabWidget);
@ -185,9 +196,9 @@ DigiSettingsPanel::DigiSettingsPanel(Digitizer ** digi, unsigned int nDigi, QStr
{//^======================= Buttons
QWidget * buttonsWidget = new QWidget(tab);
tabLayout_V1->addWidget(buttonsWidget);
QGridLayout * buttonLayout = new QGridLayout(buttonsWidget);
buttonsWidget[iDigi] = new QWidget(tab);
tabLayout_V1->addWidget(buttonsWidget[iDigi]);
QGridLayout * buttonLayout = new QGridLayout(buttonsWidget[iDigi]);
buttonLayout->setSpacing(2);
int rowID = 0 ;
@ -246,6 +257,8 @@ DigiSettingsPanel::DigiSettingsPanel(Digitizer ** digi, unsigned int nDigi, QStr
SendLogMsg("Digi-" +QString::number(digi[ID]->GetSerialNumber()) + " : AutoSetDPPEventAggregation()");
digi[ID]->AutoSetDPPEventAggregation();
UpdateBoardAndChannelsStatus();
UpdatePanelFromMemory();
emit UpdateOtherPanels();
});
// bnSendSoftwareClockSyncSignal = new QPushButton("Send SW Clock-Sync Signal", this);
@ -258,7 +271,7 @@ DigiSettingsPanel::DigiSettingsPanel(Digitizer ** digi, unsigned int nDigi, QStr
// connect(bnSaveSettingsToText, &QPushButton::clicked, this, [=](){ SaveSetting(1);});
//checkBox, to coupled or decouple the setting file.
chkCoupledSettingFile = new QCheckBox("Update Setting", this);
chkCoupledSettingFile = new QCheckBox("Live Setting Update", this);
buttonLayout->addWidget(chkCoupledSettingFile, rowID, 2);
chkCoupledSettingFile->setCheckState(Qt::CheckState::Unchecked);
connect(chkCoupledSettingFile, &QCheckBox::stateChanged, this, [=](int state){
@ -341,6 +354,7 @@ DigiSettingsPanel::DigiSettingsPanel(Digitizer ** digi, unsigned int nDigi, QStr
}
SetUpInquiryCopyTab();
CheckRadioAndCheckedButtons();
connect(tabWidget, &QTabWidget::currentChanged, this, [=](int index){
if( index < (int) nDigi) {
@ -358,7 +372,8 @@ DigiSettingsPanel::DigiSettingsPanel(Digitizer ** digi, unsigned int nDigi, QStr
//If any digitizer is running ACQ, disable the panel.
for( unsigned int iDigi = 0; iDigi < nDigi; iDigi ++){
if( digi[iDigi]->IsRunning() ) {
this->setEnabled(false);
// this->setEnabled(false);
EnableButtons(false);
break;
}
}
@ -392,7 +407,13 @@ void DigiSettingsPanel::SetUpCheckBox(QCheckBox * &chkBox, QString label, QGridL
if( !enableSignalSlot ) return;
int chID = ch < 0 ? chSelection[ID]->currentData().toInt() : ch;
digi[ID]->SetBits(para, bit, state ? 1 : 0, chID);
if( para == DPP::DisableExternalTrigger ) {
digi[ID]->SetBits(para, bit, state ? 0 : 1, chID);
}else{
digi[ID]->SetBits(para, bit, state ? 1 : 0, chID);
}
if( para.IsCoupled() == true && chID >= 0 ) digi[ID]->SetBits(para, bit, state ? 1 : 0, chID%2 == 0 ? chID + 1 : chID - 1);
UpdatePanelFromMemory();
emit UpdateOtherPanels();
@ -536,6 +557,16 @@ void DigiSettingsPanel::SetUpSpinBox(RSpinBox * &sb, QString label, QGridLayout
return;
}
if( para == DPP::DecimationFactor ){
int deci = pow(2, sb->value());
if( sbRecordLength[ID][0]->value() / digi[ID]->GetTick2ns() <= 2 * deci ){
SendLogMsg("Tried to set waveform decimation to be " + QString::number(deci) + ", which make the number of trace less than 2. Abort.");
sbSWDecimation[ID]->setValue(0);
}else{
SendLogMsg("Set waveform decimation to be " + QString::number(deci) + ".");
}
}
uint32_t bit = para.GetPartialStep() == -1 ? sb->value() : sb->value() / para.GetPartialStep() / digi[ID]->GetTick2ns();
if( para.IsCoupled() == true && chID >= 0 ) {
@ -600,6 +631,11 @@ void DigiSettingsPanel::SetUpGlobalTriggerMaskAndFrontPanelMask(QGridLayout * &
});
SetUpCheckBox(chkEnableExternalTrigger[ID], "Enable TRG-IN ", gLayout, 1, 1, DPP::DisableExternalTrigger, {1, 0});
connect(chkEnableExternalTrigger[ID], &QCheckBox::stateChanged, this, [=](int state){
cbTRGINMode[ID]->setEnabled(state);
cbTRINMezzanines[ID]->setEnabled(state);
});
///============================ Trig In mode
QLabel * trgInMode = new QLabel("TRI-In Mode ", this);
@ -626,18 +662,13 @@ void DigiSettingsPanel::SetUpGlobalTriggerMaskAndFrontPanelMask(QGridLayout * &
cbTRINMezzanines[ID] = new RComboBox(this);
gLayout->addWidget(cbTRINMezzanines[ID], 3, 1, 1, 2);
items = DPP::Bit_FrontPanelIOControl::ListTRGIMezzanine;
items = DPP::Bit_FrontPanelIOControl::ListTRGINMezzanine;
for(int i = 0; i < (int) items.size(); i++){
cbTRINMezzanines[ID]->addItem(QString::fromStdString(items[i].first), items[i].second);
}
connect( cbTRINMezzanines[ID], &RComboBox::currentIndexChanged, this, [=](int index){
if( !enableSignalSlot ) return;
digi[ID]->SetBits(DPP::FrontPanelIOControl, DPP::Bit_FrontPanelIOControl::TRGINMode, index, -1);
});
connect(chkEnableExternalTrigger[ID], &QCheckBox::stateChanged, this, [=](int state){
cbTRGINMode[ID]->setEnabled(state);
cbTRINMezzanines[ID]->setEnabled(state);
digi[ID]->SetBits(DPP::FrontPanelIOControl, DPP::Bit_FrontPanelIOControl::TRGINMezzanine, index, -1);
});
SetUpComboBox(cbAnalogMonitorMode[ID], "Analog Monitor Mode ", gLayout, 4, 0, DPP::AnalogMonitorMode, 0);
@ -1303,6 +1334,7 @@ void DigiSettingsPanel::SetUpInquiryCopyTab(){
std::vector<Reg> regList;
if( digi[fromIndex]->GetDPPType() == V1730_DPP_PHA_CODE ) regList = RegisterChannelList_PHA;
if( digi[fromIndex]->GetDPPType() == V1730_DPP_PSD_CODE ) regList = RegisterChannelList_PSD;
if( digi[fromIndex]->GetDPPType() == V1740_DPP_QDC_CODE ) regList = RegisterChannelList_QDC;
int fromCh = -1;
for( int i = 0; i < MaxRegChannel; i++) {
@ -1314,8 +1346,13 @@ void DigiSettingsPanel::SetUpInquiryCopyTab(){
if( fromCh == -1 ) return;
printf("Copy Digi-%d, ch %d \n", digi[fromIndex]->GetSerialNumber(), fromCh);
for( int i = 0; i < MaxRegChannel; i++){
if( ! chkCh[i]->isChecked() ) return;
if( !chkCh[i]->isChecked() || !chkCh[i]->isEnabled() ) continue;
printf("... to Digi-%d, ch %d \n", digi[toIndex]->GetSerialNumber(), i);
//Copy setting
for( int k = 0; k < (int) regList.size(); k ++){
if( regList[k].GetRWType() != RW::ReadWrite ) continue;
@ -1366,6 +1403,7 @@ void DigiSettingsPanel::SetUpChannelMask(unsigned int digiID){
connect(bnChEnableMask[digiID][i], &QPushButton::clicked, this, [=](){
if( !enableSignalSlot) return;
if( digi[digiID]->IsRunning() ) return;
if( bnChEnableMask[digiID][i]->styleSheet() == "" ){
bnChEnableMask[digiID][i]->setStyleSheet("background-color : green;");
@ -1524,12 +1562,13 @@ void DigiSettingsPanel::SetUpChannel_PHA(){
QWidget * jaja = new QWidget(this);
allSettingLayout->addWidget(jaja);
QHBoxLayout * papa = new QHBoxLayout(jaja);
papa->setAlignment(Qt::AlignLeft);
const unsigned short numChannel = digi[ID]->GetNumRegChannels();
{//^============================== Channel selection
QHBoxLayout * papa = new QHBoxLayout(jaja);
papa->setAlignment(Qt::AlignLeft);
QLabel * lbChSel = new QLabel ("Channel : ", this);
lbChSel->setAlignment(Qt::AlignCenter | Qt::AlignRight);
papa->addWidget(lbChSel);
@ -1542,6 +1581,16 @@ void DigiSettingsPanel::SetUpChannel_PHA(){
connect(chSelection[ID], &RComboBox::currentIndexChanged, this, [=](){
SyncAllChannelsTab_PHA();
});
bnProgramChannel[ID] = new QPushButton("Program Default Channel Settings",this);
papa->addWidget(bnProgramChannel[ID]);
connect(bnProgramChannel[ID], &QPushButton::clicked, this, [=](){
short ch = chSelection[ID]->currentData().toInt();
digi[ID]->ProgramChannel(ch);
digi[ID]->ReadAllSettingsFromBoard(true);
UpdatePanelFromMemory();
emit UpdateOtherPanels();
});
}
{//*========================= input
@ -1779,7 +1828,7 @@ void DigiSettingsPanel::SetUpChannel_PHA(){
QLabel * lb2 = new QLabel("Local Shaped Trig. [G]", this); lb2->setAlignment(Qt::AlignHCenter); tabLayout->addWidget(lb2, 0, 4);
QLabel * lb1 = new QLabel("Trig. Counter Flag [G]", this); lb1->setAlignment(Qt::AlignHCenter); tabLayout->addWidget(lb1, 0, 6);
}
SetUpSpinBox(sbShapedTrigWidth[ID][ch], "", tabLayout, ch + 1, 1, DPP::PSD::ShapedTriggerWidth, ch);
SetUpSpinBox(sbShapedTrigWidth[ID][ch], "", tabLayout, ch + 1, 1, DPP::PHA::ShapedTriggerWidth, ch);
SetUpComboBoxBit(cbLocalShapedTrigger[ID][ch], "", tabLayout, ch + 1, 3, DPP::PHA::Bit_DPPAlgorithmControl2::ListLocalShapeTrigMode, DPP::PHA::DPPAlgorithmControl2_G, DPP::PHA::Bit_DPPAlgorithmControl2::LocalShapeTriggerMode, 1, ch);
SetUpComboBoxBit(cbTrigCount[ID][ch], "", tabLayout, ch + 1, 5, DPP::PHA::Bit_DPPAlgorithmControl2::ListTrigCounter, DPP::PHA::DPPAlgorithmControl2_G, DPP::PHA::Bit_DPPAlgorithmControl2::TriggerCounterFlag, 1, ch);
SetUpCheckBox(chkTagCorrelation[ID][ch], "Tag Correlated events [G]", tabLayout, ch + 1, 7, DPP::PHA::DPPAlgorithmControl2_G, DPP::PHA::Bit_DPPAlgorithmControl2::TagCorrelatedEvents, ch);
@ -1973,12 +2022,12 @@ void DigiSettingsPanel::SetUpChannel_PSD(){
QWidget * jaja = new QWidget(this);
allSettingLayout->addWidget(jaja);
QHBoxLayout * papa = new QHBoxLayout(jaja);
papa->setAlignment(Qt::AlignLeft);
const unsigned short numChannel = digi[ID]->GetNumRegChannels();
{//^============================== Channel selection
QHBoxLayout * papa = new QHBoxLayout(jaja);
papa->setAlignment(Qt::AlignLeft);
QLabel * lbChSel = new QLabel ("Ch : ", this);
lbChSel->setAlignment(Qt::AlignCenter | Qt::AlignRight);
papa->addWidget(lbChSel);
@ -1991,6 +2040,16 @@ void DigiSettingsPanel::SetUpChannel_PSD(){
connect(chSelection[ID], &RComboBox::currentIndexChanged, this, [=](){
SyncAllChannelsTab_PSD();
});
bnProgramChannel[ID] = new QPushButton("Program Default Channel Settings",this);
papa->addWidget(bnProgramChannel[ID]);
connect(bnProgramChannel[ID], &QPushButton::clicked, this, [=](){
short ch = chSelection[ID]->currentData().toInt();
digi[ID]->ProgramChannel(ch);
digi[ID]->ReadAllSettingsFromBoard(true);
UpdatePanelFromMemory();
emit UpdateOtherPanels();
});
}
{//*=============== input
@ -2486,7 +2545,7 @@ void DigiSettingsPanel::SetUpChannel_PSD(){
QLabel * lb4 = new QLabel("Veto Width", this); lb4->setAlignment(Qt::AlignHCenter); tabLayout->addWidget(lb4, 0, 6);
QLabel * lb5 = new QLabel("Veto Step", this); lb5->setAlignment(Qt::AlignHCenter); tabLayout->addWidget(lb5, 0, 8);
}
SetUpComboBoxBit(cbVetoSource[ID][ch], "", tabLayout, ch + 1, 1, DPP::PHA::Bit_DPPAlgorithmControl2::ListVetoSource, DPP::PHA::DPPAlgorithmControl2_G, DPP::PHA::Bit_DPPAlgorithmControl2::VetoSource, 1, ch);
SetUpComboBoxBit(cbVetoSource[ID][ch], "", tabLayout, ch + 1, 1, DPP::PSD::Bit_DPPAlgorithmControl2::ListVetoSource, DPP::PSD::DPPAlgorithmControl2_G, DPP::PSD::Bit_DPPAlgorithmControl2::VetoSource, 1, ch);
SetUpComboBoxBit(cbVetoMode[ID][ch], "", tabLayout, ch + 1, 3, DPP::PSD::Bit_DPPAlgorithmControl2::ListVetoMode, DPP::PSD::DPPAlgorithmControl2_G, DPP::PSD::Bit_DPPAlgorithmControl2::VetoMode, 1, ch);
SetUpSpinBox(sbVetoWidth[ID][ch], "", tabLayout, ch + 1, 5, DPP::VetoWidth, ch);
SetUpComboBoxBit(cbVetoStep[ID][ch], "", tabLayout, ch + 1, 7, DPP::Bit_VetoWidth::ListVetoStep, DPP::VetoWidth, DPP::Bit_VetoWidth::VetoStep, 1, ch);
@ -2497,8 +2556,8 @@ void DigiSettingsPanel::SetUpChannel_PSD(){
QLabel * lb2 = new QLabel("Extra Option [G]", this); lb2->setAlignment(Qt::AlignHCenter); tabLayout->addWidget(lb2, 0, 2);
QLabel * lb3 = new QLabel("TRG-OUT Ch. Prb. [G]", this); lb3->setAlignment(Qt::AlignHCenter); tabLayout->addWidget(lb3, 0, 4);
}
SetUpComboBoxBit(cbExtra2Option[ID][ch], "", tabLayout, ch + 1, 1, DPP::PHA::Bit_DPPAlgorithmControl2::ListExtra2, DPP::PHA::DPPAlgorithmControl2_G, DPP::PHA::Bit_DPPAlgorithmControl2::Extra2Option, 2, ch);
SetUpComboBoxBit(cbTRGOUTChannelProbe[ID][ch], "", tabLayout, ch + 1, 3, DPP::PSD::Bit_DPPAlgorithmControl2::ListChannelProbe, DPP::PSD::DPPAlgorithmControl2_G, DPP::PSD::Bit_DPPAlgorithmControl2::ChannelProbe, 2, ch);
SetUpComboBoxBit(cbExtra2Option[ID][ch], "", tabLayout, ch + 1, 1, DPP::PSD::Bit_DPPAlgorithmControl2::ListExtraWordOpt, DPP::PSD::DPPAlgorithmControl2_G, DPP::PSD::Bit_DPPAlgorithmControl2::ExtraWordOption, 1, ch);
SetUpComboBoxBit(cbTRGOUTChannelProbe[ID][ch], "", tabLayout, ch + 1, 3, DPP::PSD::Bit_DPPAlgorithmControl2::ListChannelProbe, DPP::PSD::DPPAlgorithmControl2_G, DPP::PSD::Bit_DPPAlgorithmControl2::ChannelProbe, 1, ch);
}
}
@ -2521,6 +2580,10 @@ void DigiSettingsPanel::SetUpBoard_QDC(){
SetUpSpinBox(sbNumEventAgg[ID][0], "Event pre Agg. : ", bdCfgLayout[ID], 5, 0, DPP::QDC::NumberEventsPerAggregate, -1, true);
SetUpSpinBox(sbRecordLength[ID][0], "Record Length [ns] : ", bdCfgLayout[ID], 6, 0, DPP::QDC::RecordLength_W, -1, true);
SetUpSpinBox( sbSWDecimation[ID], "SW Decimation Factor : ", bdCfgLayout[ID], 7, 0, DPP::DecimationFactor, -1, true);
QLabel * lbDeci = new QLabel("This average trace.", this);
bdCfgLayout[ID]->addWidget(lbDeci, 7, 2, 1, 2);
}
void DigiSettingsPanel::SetUpChannel_QDC(){
@ -2553,12 +2616,12 @@ void DigiSettingsPanel::SetUpChannel_QDC(){
QWidget * jaja = new QWidget(this);
allSettingLayout->addWidget(jaja);
QHBoxLayout * papa = new QHBoxLayout(jaja);
papa->setAlignment(Qt::AlignLeft);
const unsigned short numGroup = digi[ID]->GetNumRegChannels();
{//^============================== Group selection
QHBoxLayout * papa = new QHBoxLayout(jaja);
papa->setAlignment(Qt::AlignLeft);
QLabel * lbChSel = new QLabel ("Group : ", this);
lbChSel->setAlignment(Qt::AlignCenter | Qt::AlignRight);
papa->addWidget(lbChSel);
@ -2570,14 +2633,21 @@ void DigiSettingsPanel::SetUpChannel_QDC(){
connect(chSelection[ID], &RComboBox::currentIndexChanged, this, [=](){
SyncAllChannelsTab_QDC();
int grpID = chSelection[ID]->currentIndex() - 1;
for( int i = 0; i < 8; i ++){
lbSubCh[ID][i] ->setText((grpID == -1 ? "Sub-Ch:" : "Ch:" )+ QString::number(grpID < 0 ? i : grpID*8 + i));
lbSubCh2[ID][i]->setText((grpID == -1 ? "Sub-Ch:" : "Ch:" )+ QString::number(grpID < 0 ? i : grpID*8 + i));
}
}
});
bnProgramChannel[ID] = new QPushButton("Program Default Channel Settings",this);
papa->addWidget(bnProgramChannel[ID]);
connect(bnProgramChannel[ID], &QPushButton::clicked, this, [=](){
short group = chSelection[ID]->currentData().toInt();
digi[ID]->ProgramChannel(group);
digi[ID]->ReadAllSettingsFromBoard(true);
UpdatePanelFromMemory();
emit UpdateOtherPanels();
});
}
@ -2690,13 +2760,22 @@ void DigiSettingsPanel::SetUpChannel_QDC(){
SetUpCheckBox(chkDisableSelfTrigger[ID][numGroup], "Disable Self Trigger ", triggerLayout, 0, 1, DPP::QDC::DPPAlgorithmControl, DPP::QDC::Bit_DPPAlgorithmControl::DisableSelfTrigger);
SetUpCheckBox(chkDisableTriggerHysteresis[ID][numGroup], "Disbale Trig. Hysteresis ", triggerLayout, 2, 1, DPP::QDC::DPPAlgorithmControl, DPP::QDC::Bit_DPPAlgorithmControl::DisableTriggerHysteresis, -1, 2);
SetUpComboBoxBit(cbTrigMode[ID][numGroup], "Trig. Mode : ", triggerLayout, 0, 2, DPP::QDC::Bit_DPPAlgorithmControl::ListTrigMode, DPP::QDC::DPPAlgorithmControl, DPP::QDC::Bit_DPPAlgorithmControl::TriggerMode);
SetUpSpinBox(sbTriggerHoldOff[ID][numGroup], "Trig. Holdoff [ns] : ", triggerLayout, 2, 2, DPP::QDC::TriggerHoldOffWidth);
SetUpSpinBox(sbShapedTrigWidth[ID][numGroup], "Trig. Out Width [ns] : ", triggerLayout, 3, 2, DPP::QDC::TRGOUTWidth);
int rowID = 4;
if( digi[ID]->HasOverThresholdWidth_QDC() ){
SetUpCheckBox(chkOverthreshold[ID][numGroup], "Enable OverThreshold Width ", triggerLayout, rowID, 1, DPP::QDC::DPPAlgorithmControl, DPP::QDC::Bit_DPPAlgorithmControl::OverThresholdWitdhEnable);
SetUpSpinBox(sbOverThresholdWidth[ID][numGroup], "OverThreshold Width [ns] :", triggerLayout, rowID, 2, DPP::QDC::OverThresholdWidth);
rowID ++;
}
/// Trigger Threshold
QGroupBox * widget = new QGroupBox("Threshold [LSB]", triggerBox);
triggerLayout->addWidget(widget, 4, 0, 1, 4);
triggerLayout->addWidget(widget, rowID, 0, 1, 4);
QGridLayout * dcLayout = new QGridLayout(widget);
dcLayout->setSpacing(2);
@ -2955,7 +3034,7 @@ void DigiSettingsPanel::SetUpChannel_QDC(){
QTabWidget * trigTab = new QTabWidget(this);
trigLayout->addWidget(trigTab);
QStringList tabName = {"Common Settings", "Threshold", "Others"};
QStringList tabName = {"Common Settings", "Threshold", "OverThreshold Width", "Others"};
const int nTab = tabName.count();
@ -3035,6 +3114,20 @@ void DigiSettingsPanel::SetUpChannel_QDC(){
}
if( i == 2 ){
if( digi[ID]->HasOverThresholdWidth_QDC() ){
if( ch == 0 ){
QLabel * lb0 = new QLabel("OverThreshold Width [ns]", this); lb0->setAlignment(Qt::AlignHCenter); tabLayout->addWidget(lb0, 0, 4);
}
SetUpCheckBox(chkOverthreshold[ID][ch], "Enable OverThreshold Width ", tabLayout, ch+1, 1, DPP::QDC::DPPAlgorithmControl, DPP::QDC::Bit_DPPAlgorithmControl::OverThresholdWitdhEnable, ch);
SetUpSpinBox(sbOverThresholdWidth[ID][ch], "", tabLayout, ch+1, 3, DPP::QDC::OverThresholdWidth, ch);
}else{
QLabel * lb0 = new QLabel("OverThreshold Width not supported.", this); lb0->setAlignment(Qt::AlignHCenter); tabLayout->addWidget(lb0, 0, 1);
}
}
if( i == 3 ){
SetUpCheckBox(chkDisableSelfTrigger[ID][ch], "Disable Self Trigger ", tabLayout, ch+1, 1, DPP::QDC::DPPAlgorithmControl, DPP::QDC::Bit_DPPAlgorithmControl::DisableSelfTrigger, ch);
SetUpCheckBox(chkDisableTriggerHysteresis[ID][ch], "Disbale Trig. Hysteresis ", tabLayout, ch+1, 3, DPP::QDC::DPPAlgorithmControl, DPP::QDC::Bit_DPPAlgorithmControl::DisableTriggerHysteresis, ch, 2);
}
@ -3043,7 +3136,7 @@ void DigiSettingsPanel::SetUpChannel_QDC(){
}
}
{//^================================== QDC
{//^================================== QDC
QVBoxLayout *trapLayout = new QVBoxLayout(chTrap);
@ -3102,7 +3195,7 @@ void DigiSettingsPanel::SetUpChannel_QDC(){
}
}
{//^======================================== Others
{//^======================================== Others
QVBoxLayout *otherLayout = new QVBoxLayout(chOthers);
QTabWidget * othersTab = new QTabWidget(this);
@ -3354,7 +3447,7 @@ void DigiSettingsPanel::UpdatePanelFromMemory(){
sbAggNum[ID]->setValue(digi[ID]->GetSettingFromMemory(DPP::MaxAggregatePerBlockTransfer));
chkEnableExternalTrigger[ID]->setChecked( ! ( digi[ID]->GetSettingFromMemory(DPP::DisableExternalTrigger) & 0x1) );
chkEnableExternalTrigger[ID]->setChecked( !( digi[ID]->GetSettingFromMemory(DPP::DisableExternalTrigger) & 0x1) );
sbRunDelay[ID]->setValue(digi[ID]->GetSettingFromMemory(DPP::RunStartStopDelay) * DPP::RunStartStopDelay.GetPartialStep() * digi[ID]->GetTick2ns());
@ -3399,6 +3492,9 @@ void DigiSettingsPanel::UpdatePanelFromMemory(){
}
}
cbTRGINMode[ID]->setCurrentIndex((frontPanel >> 10 ) & 0x1);
cbTRINMezzanines[ID]->setCurrentIndex((frontPanel >> 11 ) & 0x1);
//*========================================
uint32_t glbTrgMask = digi[ID]->GetSettingFromMemory(DPP::GlobalTriggerMask);
@ -3411,10 +3507,16 @@ void DigiSettingsPanel::UpdatePanelFromMemory(){
}
}
sbGlbMajLvl[ID]->setValue( Digitizer::ExtractBits(glbTrgMask, DPP::Bit_GlobalTriggerMask::MajorLevel) );
}
sbGlbMajCoinWin[ID]->setValue( Digitizer::ExtractBits(glbTrgMask, DPP::Bit_GlobalTriggerMask::MajorCoinWin) );
cbGlbUseOtherTriggers[ID]->setCurrentIndex(Digitizer::ExtractBits(glbTrgMask, {2, 30}));
sbGlbMajCoinWin[ID]->setValue( Digitizer::ExtractBits(glbTrgMask, DPP::Bit_GlobalTriggerMask::MajorCoinWin) * 4 * digi[ID]->GetTick2ns());
cbGlbUseOtherTriggers[ID]->setCurrentIndex(Digitizer::ExtractBits(glbTrgMask, {2, 30}));
if( sbGlbMajLvl[ID]->value() > 0 ) {
sbGlbMajCoinWin[ID]->setEnabled(true);
}else{
sbGlbMajCoinWin[ID]->setEnabled(false);
}
}
//*========================================
uint32_t TRGOUTMask = digi[ID]->GetSettingFromMemory(DPP::FrontPanelTRGOUTEnableMask);
@ -3620,6 +3722,20 @@ void DigiSettingsPanel::SyncCheckBox(QCheckBox *(&chk)[][MaxRegChannel+1]){
}
}
void DigiSettingsPanel::EnableButtons(bool enable){
for( unsigned int i = 0; i < nDigi; i++ ){
if( !enable ) {
leSaveFilePath[i]->setText("changing setting is disabled due to ACQ is running.");
leSaveFilePath[i]->setStyleSheet("color:red;");
}else{
leSaveFilePath[i]->setText((QString::fromStdString(digi[i]->GetSettingFileName())));
leSaveFilePath[i]->setStyleSheet("");
}
buttonsWidget[i]->setEnabled(enable);
}
}
void DigiSettingsPanel::SyncAllChannelsTab_PHA(){
DebugPrint("%s", "DigiSettingsPanel");
SyncSpinBox(sbRecordLength);
@ -3836,16 +3952,16 @@ void DigiSettingsPanel::UpdateSettings_PSD(){
chkRejOverRange[ID][ch]->setChecked( Digitizer::ExtractBits(dpp, DPP::Bit_DPPAlgorithmControl_PSD::RejectOverRange));
chkTestPule[ID][ch]->setChecked( Digitizer::ExtractBits(dpp, DPP::Bit_DPPAlgorithmControl_PSD::InternalTestPulse));
chkDisableOppositePulse[ID][ch]->setChecked( Digitizer::ExtractBits(dpp, DPP::Bit_DPPAlgorithmControl_PSD::DisableOppositePolarityInhibitZeroCrossingOnCFD));
chkDisableSelfTrigger[ID][ch]->setChecked( Digitizer::ExtractBits(dpp, DPP::Bit_DPPAlgorithmControl_PSD::DisableSelfTrigger));
chkRejPileUp[ID][ch]->setChecked( Digitizer::ExtractBits(dpp, DPP::Bit_DPPAlgorithmControl_PSD::RejectPileup));
chkPileUpInGate[ID][ch]->setChecked( Digitizer::ExtractBits(dpp, DPP::Bit_DPPAlgorithmControl_PSD::PileupWithinGate));
chkDisableTriggerHysteresis[ID][ch]->setChecked( Digitizer::ExtractBits(dpp, DPP::Bit_DPPAlgorithmControl_PSD::DisableTriggerHysteresis));
uint32_t dpp2 = digi[ID]->GetSettingFromMemory(DPP::PSD::DPPAlgorithmControl2_G, ch);
chkDisableOppositePulse[ID][ch]->setChecked( Digitizer::ExtractBits(dpp2, DPP::Bit_DPPAlgorithmControl_PSD::DisableOppositePolarityInhibitZeroCrossingOnCFD));
chkDisableSelfTrigger[ID][ch]->setChecked( Digitizer::ExtractBits(dpp2, DPP::Bit_DPPAlgorithmControl_PSD::DisableSelfTrigger));
chkRejPileUp[ID][ch]->setChecked( Digitizer::ExtractBits(dpp2, DPP::Bit_DPPAlgorithmControl_PSD::RejectPileup));
chkPileUpInGate[ID][ch]->setChecked( Digitizer::ExtractBits(dpp2, DPP::Bit_DPPAlgorithmControl_PSD::PileupWithinGate));
chkDisableTriggerHysteresis[ID][ch]->setChecked( Digitizer::ExtractBits(dpp2, DPP::Bit_DPPAlgorithmControl_PSD::DisableTriggerHysteresis));
chkMarkSaturation[ID][ch]->setChecked( Digitizer::ExtractBits(dpp2, DPP::PSD::Bit_DPPAlgorithmControl2::MarkSaturation));
chkResetTimestampByTRGIN[ID][ch]->setChecked( Digitizer::ExtractBits(dpp2, DPP::PSD::Bit_DPPAlgorithmControl2::ResetTimestampByTRGIN));
chkMarkSaturation[ID][ch]->setChecked( Digitizer::ExtractBits(dpp, DPP::PSD::Bit_DPPAlgorithmControl2::MarkSaturation));
chkResetTimestampByTRGIN[ID][ch]->setChecked( Digitizer::ExtractBits(dpp, DPP::PSD::Bit_DPPAlgorithmControl2::ResetTimestampByTRGIN));
UpdateComboBoxBit(cbLocalTriggerValid[ID][ch], dpp2, DPP::PSD::Bit_DPPAlgorithmControl2::LocalTrigValidMode);
UpdateComboBoxBit(cbAdditionLocalTrigValid[ID][ch], dpp2, DPP::PSD::Bit_DPPAlgorithmControl2::AdditionLocalTrigValid);
@ -3879,22 +3995,23 @@ void DigiSettingsPanel::SyncAllChannelsTab_QDC(){
DebugPrint("%s", "DigiSettingsPanel");
if( !enableSignalSlot ) return;
// SyncSpinBox(sbRecordLength);
SyncSpinBox(sbPreTrigger);
SyncSpinBox(sbDCOffset);
SyncSpinBox(sbTriggerHoldOff);
SyncSpinBox(sbShapedTrigWidth);
// SyncSpinBox(sbNumEventAgg);
SyncSpinBox(sbShortGate);
SyncSpinBox(sbGateOffset);
//SyncSpinBox(sbOverThresholdWidth);
SyncCheckBox(chkDisableSelfTrigger);
SyncCheckBox(chkDisableTriggerHysteresis);
//SyncCheckBox(chkOverthreshold);
SyncCheckBox(chkChargePedestal);
SyncCheckBox(chkTestPule);
if( digi[ID]->HasOverThresholdWidth_QDC() ){
SyncSpinBox(sbOverThresholdWidth);
SyncCheckBox(chkOverthreshold);
}
SyncComboBox(cbPolarity);
SyncComboBox(cbRCCR2Smoothing);
SyncComboBox(cbBaseLineAvg);
@ -3978,6 +4095,8 @@ void DigiSettingsPanel::UpdateSettings_QDC(){
UpdateSpinBox(sbNumEventAgg[ID][0], DPP::QDC::NumberEventsPerAggregate, -1);
UpdateSpinBox(sbSWDecimation[ID], DPP::DecimationFactor, -1);
for(int grp = 0; grp < digi[ID]->GetNumRegChannels(); grp ++){
UpdateSpinBox(sbPreTrigger[ID][grp], DPP::QDC::PreTrigger, grp);
@ -3986,7 +4105,7 @@ void DigiSettingsPanel::UpdateSettings_QDC(){
UpdateSpinBox(sbShapedTrigWidth[ID][grp], DPP::QDC::TRGOUTWidth, grp);
UpdateSpinBox(sbShortGate[ID][grp], DPP::QDC::GateWidth, grp);
UpdateSpinBox(sbGateOffset[ID][grp], DPP::QDC::GateOffset, grp);
//UpdateSpinBox(sbOverThresholdWidth[ID][grp], DPP::QDC::OverThresholdWidth, grp);
uint32_t subChMask = digi[ID]->GetSettingFromMemory(DPP::QDC::SubChannelMask, grp);
@ -4009,10 +4128,13 @@ void DigiSettingsPanel::UpdateSettings_QDC(){
chkDisableSelfTrigger[ID][grp]->setChecked( Digitizer::ExtractBits(dpp, DPP::QDC::Bit_DPPAlgorithmControl::DisableSelfTrigger) );
chkDisableTriggerHysteresis[ID][grp]->setChecked( Digitizer::ExtractBits(dpp, DPP::QDC::Bit_DPPAlgorithmControl::DisableTriggerHysteresis) );
//chkOverthreshold[ID][grp]->setChecked( Digitizer::ExtractBits(dpp, DPP::QDC::Bit_DPPAlgorithmControl::OverThresholdWitdhEnable) );
chkChargePedestal[ID][grp]->setChecked( Digitizer::ExtractBits(dpp, DPP::QDC::Bit_DPPAlgorithmControl::ChargePedestal));
chkTestPule[ID][grp]->setChecked( Digitizer::ExtractBits(dpp, DPP::QDC::Bit_DPPAlgorithmControl::InternalTestPulse));
if( digi[ID]->HasOverThresholdWidth_QDC() ) {
UpdateSpinBox(sbOverThresholdWidth[ID][grp], DPP::QDC::OverThresholdWidth, grp);
chkOverthreshold[ID][grp]->setChecked( Digitizer::ExtractBits(dpp, DPP::QDC::Bit_DPPAlgorithmControl::OverThresholdWitdhEnable) );
}
uint32_t dcOffSet_low = digi[ID]->GetSettingFromMemory(DPP::QDC::DCOffset_LowCh, grp);
@ -4060,17 +4182,29 @@ void DigiSettingsPanel::CheckRadioAndCheckedButtons(){
int id1 = cbFromBoard->currentIndex();
int id2 = cbToBoard->currentIndex();
for( int i = 0 ; i < MaxRegChannel; i++){
if( i >= digi[id1]->GetNumRegChannels() ) rbCh[i]->setEnabled(false);
if( i >= digi[id2]->GetNumRegChannels() ) chkCh[i]->setEnabled(false);
if( digi[id1]->GetDPPType() == DPPTypeCode::DPP_QDC_CODE ){
bnCopyChannel->setText("Copy Group(s)");
}else{
bnCopyChannel->setText("Copy Channel(s)");
}
if( digi[id1]->GetDPPType() != digi[id2]->GetDPPType() ){
bnCopyBoard->setEnabled(false);
bnCopyChannel->setEnabled(false);
for( int i = 0 ; i < MaxRegChannel; i++){
rbCh[i]->setEnabled(false);
chkCh[i]->setEnabled(false);
}
return;
}
for( int i = 0 ; i < MaxRegChannel; i++){
rbCh[i]->setEnabled(i < digi[id1]->GetNumRegChannels());
chkCh[i]->setEnabled(i < digi[id1]->GetNumRegChannels());
}
if( id1 == id2 ){
bnCopyBoard->setEnabled(false);
}else{

View File

@ -33,6 +33,8 @@ public slots:
void SaveSetting(int opt);
void LoadSetting();
void EnableButtons(bool enable);
signals:
void SendLogMsg(const QString &msg);
void UpdateOtherPanels();
@ -69,7 +71,6 @@ private:
void SyncComboBox(RComboBox *(&cb)[][MaxRegChannel+1]);
void SyncCheckBox(QCheckBox *(&chk)[][MaxRegChannel+1]);
void SyncAllChannelsTab_PHA();
void UpdateSettings_PHA();
void SyncAllChannelsTab_PSD();
@ -102,6 +103,8 @@ private:
QLineEdit * leSaveFilePath[MaxNDigitizer];
QWidget * buttonsWidget[MaxNDigitizer];
QPushButton * bnRefreshSetting; // read setting from board
QPushButton * bnProgramPreDefined;
QPushButton * bnClearBuffer;
@ -122,6 +125,9 @@ private:
QGridLayout * bdTriggerLayout[MaxNDigitizer];
QGridLayout * bdLVDSLayout[MaxNDigitizer];
// RComboBox * cbSWDecimation[MaxNDigitizer]; // software decimation
RSpinBox * sbSWDecimation[MaxNDigitizer];
QCheckBox * chkAutoDataFlush[MaxNDigitizer];
QCheckBox * chkDecimateTrace[MaxNDigitizer];
QCheckBox * chkTrigPropagation[MaxNDigitizer];
@ -192,6 +198,7 @@ private:
QTabWidget * chTab;
RComboBox * chSelection[MaxNDigitizer];
QPushButton * bnProgramChannel[MaxNDigitizer];
//----------- common for PHA and PSD
RSpinBox * sbRecordLength[MaxNDigitizer][MaxRegChannel + 1];
@ -287,8 +294,8 @@ private:
//Trig Hold off with -> sbTriggerHoldOff
//Trig out width -> sbShapedTrigWidth
//QCheckBox * chkOverthreshold[MaxNDigitizer][MaxRegChannel+1]; //TODO need firmware version 4.25 & 135.17
//RSpinBox * sbOverThresholdWidth[MaxNDigitizer][MaxRegChannel + 1];
QCheckBox * chkOverthreshold[MaxNDigitizer][MaxRegChannel+1]; //TODO need firmware version 4.25 & 135.17
RSpinBox * sbOverThresholdWidth[MaxNDigitizer][MaxRegChannel + 1];
QPushButton * pbSubChMask[MaxNDigitizer][MaxRegChannel+1][8];
RSpinBox * sbSubChOffset[MaxNDigitizer][MaxRegChannel + 1][8];
RSpinBox * sbSubChThreshold[MaxNDigitizer][MaxRegChannel + 1][8];

11
FSUDAQ Executable file
View File

@ -0,0 +1,11 @@
#!/bin/bash
timestamp=$(date +%Y%m%d_%H%M%S)
outFile=log/program_${timestamp}.log
mkdir -p "$(dirname "$outFile")"
echo "FSUDAQ, save stdout to $outFile"
stdbuf -oL ./FSUDAQ_Qt6 | tee $outFile

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,5 @@
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#ifndef FSUDAQ_H
#define FSUDAQ_H
#include <QMainWindow>
#include <QWidget>
@ -20,12 +20,14 @@
#include "ClassInfluxDB.h"
#include "analyzers/Analyser.h"
//^#===================================================== MainWindow
class MainWindow : public QMainWindow{
class ScalarWorker; //Forward declaration
//^#===================================================== FSUDAQ
class FSUDAQ : public QMainWindow{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
FSUDAQ(QWidget *parent = nullptr);
~FSUDAQ();
void closeEvent(QCloseEvent * event){
if( scope ) {
@ -36,9 +38,9 @@ public:
delete digiSettings;
digiSettings = nullptr;
}
if( canvas ) {
delete canvas;
canvas = nullptr;
if( singleHistograms ) {
delete singleHistograms;
singleHistograms = nullptr;
}
if( onlineAnalyzer ) {
delete onlineAnalyzer;
@ -47,6 +49,9 @@ public:
event->accept();
}
public slots:
void UpdateScalar();
private slots:
void OpenDataPath();
@ -64,7 +69,6 @@ private slots:
void SetupScalar();
void CleanUpScalar();
void OpenScalar();
void UpdateScalar();
void StartACQ();
void StopACQ();
@ -76,7 +80,7 @@ private slots:
void OpenDigiSettings();
void OpenCanvas();
void OpenSingleHistograms();
void OpenAnalyzer();
@ -96,6 +100,7 @@ private:
Digitizer ** digi;
unsigned int nDigi;
bool isACQStarted;
QString programSettingsFilePath;
QString rawDataPath;
@ -139,12 +144,16 @@ private:
//@----- Elog
QString elogIP;
QString elogPort;
QString elogName;
QString elogUser;
QString elogPWD;
QLineEdit * leElogIP;
QLineEdit * leElogName;
QCheckBox * chkInflux;
QCheckBox * chkElog;
//@----- log msg
QPlainTextEdit * logInfo;
void LogMsg(QString msg);
@ -165,7 +174,13 @@ private:
//@----- Scalar
QMainWindow * scalar;
QGridLayout * scalarLayout;
TimingThread * scalarThread;
TimingThread * scalarTimingThread;
// QThread * scalarThread;
// ScalarWorker * scalarWorker;
// QTimer * scalarTimer;
// TimingThread * scalarThread;
QLineEdit *** leTrigger; // need to delete manually
QLineEdit *** leAccept; // need to delete manually
QPushButton * runStatus[MaxNDigitizer];
@ -190,14 +205,45 @@ private:
DigiSettingsPanel * digiSettings;
//@----- SingleSpectra
SingleSpectra * canvas;
TimingThread * histThread;
SingleSpectra * singleHistograms;
//@----- Analyzer
Analyzer * onlineAnalyzer;
QString maskText(const QString &password) {
if (password.length() <= 3) {
return password; // No masking needed for short passwords
} else if (password.length() <= 10) {
QString maskedPassword = password.left(3);
maskedPassword += QString("*").repeated(password.length() - 3);
return maskedPassword;
} else {
return password.left(3) + QString("*").repeated(7);
}
}
};
//^======================== Scalar Worker
// class ScalarWorker : public QObject{
// Q_OBJECT
// public:
// ScalarWorker(FSUDAQ * parent): SS(parent){}
// public slots:
// void UpdateScalar(){
// SS->UpdateScalar();
// emit workDone();
// }
// signals:
// void workDone();
// private:
// FSUDAQ * SS;
// };
#endif // MAINWINDOW_H

View File

@ -11,9 +11,9 @@ QT += core widgets charts printsupport
LIBS += -lCAENDigitizer -lcurl
#==== for enable GDB debug
#QMAKE_CXXFLAGS += -g
#QMAKE_CXXFLAGS_RELEASE = -O0
#QMAKE_CFLAGS_RELEASE = -O0
QMAKE_CXXFLAGS += -g
QMAKE_CXXFLAGS_RELEASE = -O0
QMAKE_CFLAGS_RELEASE = -O0
# You can make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
@ -25,26 +25,29 @@ LIBS += -lCAENDigitizer -lcurl
# Input
HEADERS += ClassData.h \
ClassDigitizer.h \
ClassInfluxDB.h\
CustomThreads.h \
CustomWidgets.h \
Histogram1D.h \
Histogram2D.h \
DigiSettingsPanel.h \
FSUDAQ.h \
macro.h \
RegisterAddress.h \
ClassInfluxDB.h\
Scope.h \
SingleSpectra.h \
Histogram1D.h \
Histogram2D.h \
Hit.h \
macro.h \
MultiBuilder.h \
qcustomplot.h \
analyzers/Isotope.h \
RegisterAddress.h \
Scope.h \
SingleSpectra.h \
analyzers/Analyser.h \
analyzers/CoincidentAnalyzer.h \
analyzers/SplitPoleAnalyzer.h \
analyzers/Cross.h\
analyzers/EncoreAnalyzer.h \
analyzers/RAISOR.h
analyzers/Isotope.h \
analyzers/SplitPoleAnalyzer.h \
analyzers/MUSICAnalyzer.h \
analyzers/NeutronGamma.h
SOURCES += ClassDigitizer.cpp \
DigiSettingsPanel.cpp \
FSUDAQ.cpp \

View File

@ -15,6 +15,8 @@ public:
// DebugPrint("%s", "Histogram1D");
isLogY = false;
for( int i = 0; i < MaxNHist; i++ ) showHist[i] = true;
for( int i = 0; i < 3; i ++) txt[i] = nullptr;
nData = 1;
Rebin(xbin, xmin, xmax);
@ -86,12 +88,15 @@ public:
QAction * a1 = menu.addAction("UnZoom");
QAction * a5 = menu.addAction("Set/UnSet Log-y");
QAction * a6 = nullptr;
if( nData > 1 ) a6 = menu.addAction("Toggle lines display");
QAction * a2 = menu.addAction("Clear hist.");
QAction * a3 = menu.addAction("Toggle Stat.");
QAction * a4 = menu.addAction("Rebin (clear histogram)");
//TODO fitGuass
QAction *selectedAction = menu.exec(event->globalPosition().toPoint());
//*========================================== UnZoom
if( selectedAction == a1 ){
xAxis->setRangeLower(xMin);
xAxis->setRangeUpper(xMax);
@ -101,11 +106,13 @@ public:
usingMenu = false;
}
//*========================================== Clear Hist
if( selectedAction == a2 ){
Clear();
usingMenu = false;
}
//*========================================== Toggle Stat.
if( selectedAction == a3 ){
for( int i = 0; i < 3; i++){
txt[i]->setVisible( !txt[i]->visible());
@ -113,6 +120,7 @@ public:
replot();
usingMenu = false;
}
//*========================================== Rebin
if( selectedAction == a4 ){
QDialog dialog(this);
dialog.setWindowTitle("Rebin histogram");
@ -145,25 +153,25 @@ public:
double number[3];
QObject::connect(&buttonBox, &QDialogButtonBox::accepted, [&]() {
int OKcount = 0;
bool conversionOk = true;
for( int i = 0; i < 3; i++ ){
number[i] = lineEdit[i]->text().toDouble(&conversionOk);
if( conversionOk ){
OKcount++;
}else{
msg->setText(nameList[i] + " is invalid.");
return;
}
int OKcount = 0;
bool conversionOk = true;
for( int i = 0; i < 3; i++ ){
number[i] = lineEdit[i]->text().toDouble(&conversionOk);
if( conversionOk ){
OKcount++;
}else{
msg->setText(nameList[i] + " is invalid.");
return;
}
}
if( OKcount == 3 ) {
if( number[2] > number[1] ) {
dialog.accept();
}else{
msg->setText(nameList[2] + " is smaller than " + nameList[1]);
}
if( OKcount == 3 ) {
if( number[2] > number[1] ) {
dialog.accept();
}else{
msg->setText(nameList[2] + " is smaller than " + nameList[1]);
}
}
});
QObject::connect(&buttonBox, &QDialogButtonBox::rejected, [&]() { dialog.reject();});
@ -174,8 +182,38 @@ public:
}
}
if( selectedAction == a5 ){
//*========================================== Toggle line Display
if( selectedAction == a6 ){
QDialog dialog(this);
dialog.setWindowTitle("Toggle lines Display");
QFormLayout layout(&dialog);
QCheckBox ** cbline = new QCheckBox *[nData];
for( int i = 0; i < nData; i++ ){
cbline[i] = new QCheckBox(graph(i)->name(), &dialog);
layout.addRow(cbline[i]);
if( showHist[i] ) cbline[i]->setChecked(true);
}
QDialogButtonBox buttonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, &dialog);
layout.addRow(&buttonBox);
QObject::connect(&buttonBox, &QDialogButtonBox::accepted, [&]() {
for( int i = 0; i < nData; i++ ){
showHist[i] = cbline[i]->isChecked();
}
dialog.accept();
});
QObject::connect(&buttonBox, &QDialogButtonBox::rejected, [&]() { dialog.reject();});
if( dialog.exec() == QDialog::Accepted ){
UpdatePlot();
}
}
//*========================================== Set Log y
if( selectedAction == a5 ){
if( !isLogY ){
this->yAxis->setScaleType(QCPAxis::stLogarithmic);
isLogY = true;
@ -206,12 +244,16 @@ public:
addGraph();
graph(nData - 1)->setName(title);
SetColor(color, nData-1);
yList[nData-1] = yList[0];
yList[nData-1].clear();
for( int i = 0; i < xList.count(); i++) yList[nData-1].append(0);
}
void UpdatePlot(){
DebugPrint("%s", "Histogram1D");
for( int ID = 0 ; ID < nData; ID ++) graph(ID)->setData(xList, yList[ID]);
for( int ID = 0 ; ID < nData; ID ++) {
graph(ID)->setVisible(showHist[ID]);
graph(ID)->setData(xList, yList[ID]);
}
xAxis->setRangeLower(xMin);
xAxis->setRangeUpper(xMax);
yAxis->setRangeLower(0);
@ -222,7 +264,7 @@ public:
void Clear(){
DebugPrint("%s", "Histogram1D");
for( int ID = 0 ; ID < nData; ID ++) {
for( int i = 0; i <= yList[ID].count(); i++) yList[ID][i] = 0;
for( int i = 0; i < xList.count(); i++) yList[ID][i] = 0;
}
yMax = 0;
txt[0]->setText("Under Flow : 0");
@ -234,13 +276,15 @@ public:
UpdatePlot();
}
void SetXTitle(QString xTitle) { xAxis->setLabel(xTitle); }
void SetLineTitle(QString title, int lineID = 0) { graph(lineID)->setName(title); }
void SetXTitle(QString xTitle) { xAxis->setLabel(xTitle);}
void Rebin(int xbin, double xmin, double xmax){
// DebugPrint("%s", "Histogram1D");
xMin = xmin;
xMax = xmax;
xBin = xbin;
if( xBin > 1000) xBin = 1000;
dX = (xMax - xMin)/(xBin);
@ -283,16 +327,18 @@ public:
txt[2]->setText("Over Flow : "+ QString::number(overFlow));
return;
}
}else{
if( value < xMin || value > xMax ) return;
}
double bin = (value - xMin)/dX;
int index1 = 2*qFloor(bin) + 1;
int bin = qFloor((value - xMin)/dX);
int index1 = 2*bin + 1;
int index2 = index1 + 1;
if( 0 <= index1 && index1 <= 2*xBin) yList[ID][index1] += 1;
if( 0 <= index1 && index2 <= 2*xBin) yList[ID][index2] += 1;
if( yList[ID][index1] > yMax ) yMax = yList[ID][index1];
if( showHist[ID] && yList[ID][index1] > yMax ) yMax = yList[ID][index1];
}
void Print(unsigned int ID = 0){
@ -324,6 +370,8 @@ private:
bool usingMenu;
bool showHist[MaxNHist];
};

View File

@ -19,200 +19,20 @@ const QList<QPair<QColor, QString>> colorCycle = { {QColor(Qt::red), "Red"},
class Histogram2D : public QCustomPlot{
public:
Histogram2D(QString title, QString xLabel, QString yLabel, int xbin, double xmin, double xmax, int ybin, double ymin, double ymax, QWidget * parent = nullptr) : QCustomPlot(parent){
// DebugPrint("%s", "Histogram2D");
for( int i = 0; i < 3; i ++ ){
for( int j = 0; j < 3; j ++ ){
box[i][j] = nullptr;
txt[i][j] = nullptr;
}
}
Histogram2D(QString title, QString xLabel, QString yLabel,
int xbin, double xmin, double xmax,
int ybin, double ymin, double ymax,
QWidget * parent = nullptr,
QString defaultPath = QDir::homePath());
isChannelMap = false;
tickStep = 1; // only used when isChannelMap = true
isLogZ = false;
axisRect()->setupFullAxesBox(true);
xAxis->setLabel(xLabel);
yAxis->setLabel(yLabel);
colorMap = new QCPColorMap(xAxis, yAxis);
Rebin(xbin, xmin, xmax, ybin, ymin, ymax);
colorMap->setInterpolate(false);
QCPTextElement *titleEle = new QCPTextElement(this, title, QFont("sans", 12));
plotLayout()->insertRow(0);
plotLayout()->addElement(0, 0, titleEle);
colorScale = new QCPColorScale(this);
plotLayout()->addElement(1, 1, colorScale);
colorScale->setType(QCPAxis::atRight);
colorMap->setColorScale(colorScale);
QCPColorGradient color;
color.setNanHandling(QCPColorGradient::NanHandling::nhNanColor);
color.setNanColor(QColor("white"));
color.clearColorStops();
// color.setColorStopAt( 0.0, QColor("white" ));
color.setColorStopAt( 0.0, QColor("purple" ));
color.setColorStopAt( 0.2, QColor("blue"));
color.setColorStopAt( 0.4, QColor("cyan"));
color.setColorStopAt( 0.6, QColor("green"));
color.setColorStopAt( 0.8, QColor("yellow"));
color.setColorStopAt( 1.0, QColor("red"));
colorMap->setGradient(color);
double xPosStart = 0.02;
double xPosStep = 0.07;
double yPosStart = 0.02;
double yPosStep = 0.05;
for( int i = 0; i < 3; i ++ ){
for( int j = 0; j < 3; j ++ ){
box[i][j] = new QCPItemRect(this);
box[i][j]->topLeft->setType(QCPItemPosition::ptAxisRectRatio);
box[i][j]->topLeft->setCoords(xPosStart + xPosStep*i, yPosStart + yPosStep*j);
box[i][j]->bottomRight->setType(QCPItemPosition::ptAxisRectRatio);
box[i][j]->bottomRight->setCoords(xPosStart + xPosStep*(i+1), yPosStart + yPosStep*(j+1));
txt[i][j] = new QCPItemText(this);
txt[i][j]->setPositionAlignment(Qt::AlignLeft);
txt[i][j]->position->setType(QCPItemPosition::ptAxisRectRatio);
txt[i][j]->position->setCoords(xPosStart + xPosStep/2 + xPosStep*i, yPosStart + yPosStep*j);;
txt[i][j]->setText("0");
txt[i][j]->setFont(QFont("Helvetica", 9));
}
}
cutList.clear();
cutEntryList.clear();
rescaleAxes();
usingMenu = false;
isDrawCut = false;
tempCutID = -1;
numCut = 0;
lastPlottableID = -1;
line = new QCPItemLine(this);
line->setPen(QPen(Qt::gray, 1, Qt::DashLine));
line->setVisible(false);
isBusy = false;
connect(this, &QCustomPlot::mouseMove, this, [=](QMouseEvent *event){
double x = xAxis->pixelToCoord(event->pos().x());
double y = yAxis->pixelToCoord(event->pos().y());
int xI, yI;
colorMap->data()->coordToCell(x, y, &xI, &yI);
double z = colorMap->data()->cell(xI, yI);
QString coordinates = QString("X: %1, Y: %2, Z: %3").arg(x).arg(y).arg(z);
QToolTip::showText(event->globalPosition().toPoint(), coordinates, this);
//when drawing cut, show dashhed line
if( isDrawCut && tempCut.size() > 0 ){
line->end->setCoords(x,y);
line->setVisible(true);
replot();
}
});
connect(this, &QCustomPlot::mousePress, this, [=](QMouseEvent * event){
if (event->button() == Qt::LeftButton && !usingMenu && !isDrawCut){
setSelectionRectMode(QCP::SelectionRectMode::srmZoom);
}
if (event->button() == Qt::LeftButton && isDrawCut){
oldMouseX = xAxis->pixelToCoord(event->pos().x());
oldMouseY = yAxis->pixelToCoord(event->pos().y());
tempCut.push_back(QPointF(oldMouseX,oldMouseY));
line->start->setCoords(oldMouseX, oldMouseY);
line->end->setCoords(oldMouseX, oldMouseY);
line->setVisible(true);
DrawCut();
}
//^================= right click
if (event->button() == Qt::RightButton) rightMouseClickMenu(event);
});
//connect( this, &QCustomPlot::mouseDoubleClick, this, [=](QMouseEvent *event){
connect( this, &QCustomPlot::mouseDoubleClick, this, [=](){
if( isDrawCut) {
tempCut.push_back(tempCut[0]);
DrawCut();
isDrawCut = false;
line->setVisible(false);
plottableIDList.push_back(plottableCount() -1 );
cutNameList.push_back("Cut-" + QString::number(cutList.count()));
cutEntryList.push_back(0);
QCPItemText * text = new QCPItemText(this);
text->setText(cutNameList.last());
text->position->setCoords(tempCut[0].rx(), tempCut[0].ry());
int colorID = tempCutID% colorCycle.count();
text->setColor(colorCycle[colorID].first);
cutTextIDList.push_back(itemCount() - 1);
replot();
cutList.push_back(tempCut);
cutIDList.push_back(tempCutID);
// qDebug() << "----------- end of create cut";
// qDebug() << " cutIDList " << cutIDList ;
// qDebug() << "plottableIDList " << plottableIDList << ", " << plottableCount();
// qDebug() << " cutTextIDList " << cutTextIDList << ", " << itemCount();
}
});
connect(this, &QCustomPlot::mouseRelease, this, [=](){
});
}
//^===================================
void SetXTitle(QString xTitle) { xAxis->setLabel(xTitle); }
void SetYTitle(QString yTitle) { yAxis->setLabel(yTitle); }
void SetXTitle(QString xTitle) { xAxis->setLabel(xTitle);}
void SetYTitle(QString yTitle) { yAxis->setLabel(yTitle);}
void Rebin(int xbin, double xmin, double xmax, int ybin, double ymin, double ymax);
void RebinY(int ybin, double ymin, double ymax);
void SetChannelMap(bool onOff, int tickStep = 1) { isChannelMap = onOff; this->tickStep = tickStep;}
void UpdatePlot(){
// QCPColorGradient color;
// color.clearColorStops();
// color.setNanColor(QColor("white"));
// // color.setColorStopAt( 0.0, QColor("white" ));
// // color.setColorStopAt( 1.0/entry[1][1], QColor("purple" ));
// color.setColorStopAt( 0.0, QColor("purple" ));
// color.setColorStopAt( 0.2, QColor("blue"));
// color.setColorStopAt( 0.4, QColor("cyan"));
// color.setColorStopAt( 0.6, QColor("green"));
// color.setColorStopAt( 0.8, QColor("yellow"));
// color.setColorStopAt( 1.0, QColor("red"));
// colorMap->setGradient(color);
colorMap->rescaleDataRange();
replot();
}
void UpdatePlot(){ colorMap->rescaleDataRange(true); replot(); }
void Clear(); // Clear Data and histrogram
void Fill(double x, double y);
@ -232,6 +52,9 @@ public:
double GetYMin() const {return yMin;}
double GetYMax() const {return yMax;}
void SaveCuts(QString cutFileName);
void LoadCuts(QString cutFileName);
private:
double xMin, xMax, yMin, yMax;
int xBin, yBin;
@ -252,15 +75,15 @@ private:
QPolygonF tempCut;
int tempCutID; // only incresing;
QList<QPolygonF> cutList;
QList<int> cutIDList;
int numCut;
QList<QPolygonF> cutList;
QList<QString> cutNameList; // name of the cut
QList<int> cutEntryList; // number of entry inside the cut.
QList<int> cutIDList; // ID of the cut
QList<int> cutTextIDList; //
QList<int> plottableIDList;
bool isDrawCut;
int lastPlottableID;
QList<int> cutTextIDList;
QList<int> plottableIDList;
QList<QString> cutNameList;
QList<int> cutEntryList;
QCPItemLine * line;
double oldMouseX = 0.0, oldMouseY = 0.0;
@ -270,11 +93,181 @@ private:
void rightMouseClickMenu(QMouseEvent * event);
void rightMouseClickRebin();
QString settingPath;
};
//^###############################################
//^###############################################
inline Histogram2D::Histogram2D(QString title, QString xLabel, QString yLabel, int xbin, double xmin, double xmax, int ybin, double ymin, double ymax, QWidget * parent, QString defaultPath) : QCustomPlot(parent){
// DebugPrint("%s", "Histogram2D");
settingPath = defaultPath;
for( int i = 0; i < 3; i ++ ){
for( int j = 0; j < 3; j ++ ){
box[i][j] = nullptr;
txt[i][j] = nullptr;
}
}
isChannelMap = false;
tickStep = 1; // only used when isChannelMap = true
isLogZ = false;
axisRect()->setupFullAxesBox(true);
xAxis->setLabel(xLabel);
yAxis->setLabel(yLabel);
colorMap = new QCPColorMap(xAxis, yAxis);
Rebin(xbin, xmin, xmax, ybin, ymin, ymax);
colorMap->setInterpolate(false);
QCPTextElement *titleEle = new QCPTextElement(this, title, QFont("sans", 12));
plotLayout()->insertRow(0);
plotLayout()->addElement(0, 0, titleEle);
colorScale = new QCPColorScale(this);
plotLayout()->addElement(1, 1, colorScale);
colorScale->setType(QCPAxis::atRight);
colorMap->setColorScale(colorScale);
QCPColorGradient color;
color.setNanHandling(QCPColorGradient::NanHandling::nhNanColor);
color.setNanColor(QColor(0,0,0,0));
color.clearColorStops();
// color.setColorStopAt( 0.0, QColor("white" ));
color.setColorStopAt( 0.0, QColor("purple" ));
color.setColorStopAt( 0.2, QColor("blue"));
color.setColorStopAt( 0.4, QColor("cyan"));
color.setColorStopAt( 0.6, QColor("green"));
color.setColorStopAt( 0.8, QColor("yellow"));
color.setColorStopAt( 1.0, QColor("red"));
colorMap->setGradient(color);
double xPosStart = 0.02;
double xPosStep = 0.07;
double yPosStart = 0.02;
double yPosStep = 0.05;
for( int i = 0; i < 3; i ++ ){
for( int j = 0; j < 3; j ++ ){
box[i][j] = new QCPItemRect(this);
box[i][j]->topLeft->setType(QCPItemPosition::ptAxisRectRatio);
box[i][j]->topLeft->setCoords(xPosStart + xPosStep*i, yPosStart + yPosStep*j);
box[i][j]->bottomRight->setType(QCPItemPosition::ptAxisRectRatio);
box[i][j]->bottomRight->setCoords(xPosStart + xPosStep*(i+1), yPosStart + yPosStep*(j+1));
txt[i][j] = new QCPItemText(this);
txt[i][j]->setPositionAlignment(Qt::AlignLeft);
txt[i][j]->position->setType(QCPItemPosition::ptAxisRectRatio);
txt[i][j]->position->setCoords(xPosStart + xPosStep/2 + xPosStep*i, yPosStart + yPosStep*j);;
txt[i][j]->setText("0");
txt[i][j]->setFont(QFont("Helvetica", 9));
}
}
cutList.clear();
cutEntryList.clear();
rescaleAxes();
usingMenu = false;
isDrawCut = false;
tempCutID = -1;
numCut = 0;
lastPlottableID = -1;
line = new QCPItemLine(this);
line->setPen(QPen(Qt::gray, 1, Qt::DashLine));
line->setVisible(false);
isBusy = false;
connect(this, &QCustomPlot::mouseMove, this, [=](QMouseEvent *event){
double x = xAxis->pixelToCoord(event->pos().x());
double y = yAxis->pixelToCoord(event->pos().y());
int xI, yI;
colorMap->data()->coordToCell(x, y, &xI, &yI);
double z = colorMap->data()->cell(xI, yI);
QString coordinates = QString("X: %1, Y: %2, Z: %3").arg(x).arg(y).arg(z);
QToolTip::showText(event->globalPosition().toPoint(), coordinates, this);
//when drawing cut, show dashhed line
if( isDrawCut && tempCut.size() > 0 ){
line->end->setCoords(x,y);
line->setVisible(true);
replot();
}
});
connect(this, &QCustomPlot::mousePress, this, [=](QMouseEvent * event){
if (event->button() == Qt::LeftButton && !usingMenu && !isDrawCut){
setSelectionRectMode(QCP::SelectionRectMode::srmZoom);
}
if (event->button() == Qt::LeftButton && isDrawCut){
oldMouseX = xAxis->pixelToCoord(event->pos().x());
oldMouseY = yAxis->pixelToCoord(event->pos().y());
tempCut.push_back(QPointF(oldMouseX,oldMouseY));
line->start->setCoords(oldMouseX, oldMouseY);
line->end->setCoords(oldMouseX, oldMouseY);
line->setVisible(true);
DrawCut();
}
//^================= right click
if (event->button() == Qt::RightButton) rightMouseClickMenu(event);
});
//connect( this, &QCustomPlot::mouseDoubleClick, this, [=](QMouseEvent *event){
connect( this, &QCustomPlot::mouseDoubleClick, this, [=](){
if( isDrawCut) {
tempCut.push_back(tempCut[0]);
DrawCut();
isDrawCut = false;
line->setVisible(false);
plottableIDList.push_back(plottableCount() -1 );
cutNameList.push_back("Cut-" + QString::number(cutList.count()));
cutEntryList.push_back(0);
QCPItemText * text = new QCPItemText(this);
text->setText(cutNameList.last());
text->position->setCoords(tempCut[0].rx(), tempCut[0].ry());
int colorID = tempCutID% colorCycle.count();
text->setColor(colorCycle[colorID].first);
cutTextIDList.push_back(itemCount() - 1);
replot();
cutList.push_back(tempCut);
cutIDList.push_back(tempCutID);
// qDebug() << "----------- end of create cut";
// qDebug() << " cutIDList " << cutIDList ;
// qDebug() << "plottableIDList " << plottableIDList << ", " << plottableCount();
// qDebug() << " cutTextIDList " << cutTextIDList << ", " << itemCount();
}
});
connect(this, &QCustomPlot::mouseRelease, this, [=](){
});
}
inline void Histogram2D::Fill(double x, double y){
// DebugPrint("%s", "Histogram2D");
if( isBusy ) return;
@ -315,6 +308,9 @@ inline void Histogram2D::Rebin(int xbin, double xmin, double xmax, int ybin, do
xBin = xbin + 2;
yBin = ybin + 2;
if( xBin > 1002) xBin = 1002;
if( yBin > 1002) yBin = 1002;
colorMap->data()->clear();
colorMap->data()->setSize(xBin, yBin);
colorMap->data()->setRange(QCPRange(xMin, xMax), QCPRange(yMin, yMax));
@ -338,6 +334,9 @@ inline void Histogram2D::Rebin(int xbin, double xmin, double xmax, int ybin, do
}
}
rescaleAxes();
UpdatePlot();
}
inline void Histogram2D::RebinY(int ybin, double ymin, double ymax){
@ -388,7 +387,7 @@ inline void Histogram2D::ClearAllCuts(){
inline void Histogram2D::PrintCutEntry() const{
DebugPrint("%s", "Histogram2D");
if( numCut == 0 ) return;
printf("=============== There are %d cuts.\n", numCut);
printf("=============== There are %d cuts. (%lld, %lld)\n", numCut, cutList.count(), cutEntryList.count());
for( int i = 0; i < cutList.count(); i++){
if( cutList[i].isEmpty() ) continue;
printf("%10s | %d \n", cutNameList[i].toStdString().c_str(), cutEntryList[i]);
@ -420,7 +419,7 @@ inline void Histogram2D::DrawCut(){
}
replot();
//qDebug() << "Plottable count : " << plottableCount() << ", cutList.count :" << cutList.count() << ", cutID :" << lastPlottableID;
// qDebug() << "Plottable count : " << plottableCount() << ", cutList.count :" << cutList.count() << ", cutID :" << lastPlottableID;
}
inline void Histogram2D::rightMouseClickMenu(QMouseEvent * event){
@ -436,11 +435,17 @@ inline void Histogram2D::rightMouseClickMenu(QMouseEvent * event){
QAction * a2 = menu->addAction("Clear hist.");
QAction * a3 = menu->addAction("Toggle Stat.");
QAction * a4 = menu->addAction("Rebin (clear histogram)");
QAction * a8 = menu->addAction("Load Cut(s)");
QAction * a5 = menu->addAction("Create a Cut");
QAction * b0 = nullptr;
QAction * b1 = nullptr;
QAction * b2 = nullptr;
if( numCut > 0 ) {
menu->addSeparator();
menu->addAction("Add/Edit names to Cuts");
menu->addAction("Clear all Cuts");
b0 = menu->addAction("Save Cut(s)");
b2 = menu->addAction("Add/Edit names to Cuts");
b1 = menu->addAction("Clear all Cuts");
}
for( int i = 0; i < cutList.size(); i++){
if( cutList[i].isEmpty()) continue;
@ -450,20 +455,25 @@ inline void Histogram2D::rightMouseClickMenu(QMouseEvent * event){
QAction *selectedAction = menu->exec(event->globalPosition().toPoint());
// qDebug() << "=======================";
// qDebug() << selectedAction;
// qDebug() << b2;
if( selectedAction == nullptr ){
usingMenu = false;
return;
}
if( selectedAction == a1 ){
xAxis->setRangeLower(xMin);
xAxis->setRangeUpper(xMax);
yAxis->setRangeLower(yMin);
yAxis->setRangeUpper(yMax);
replot();
usingMenu = false;
return;
}
if( selectedAction == a2 ) {
Clear();
usingMenu = false;
return;
}
if( selectedAction == a3 ){
@ -474,23 +484,17 @@ inline void Histogram2D::rightMouseClickMenu(QMouseEvent * event){
}
}
replot();
usingMenu = false;
return;
}
if( selectedAction == a4){
rightMouseClickRebin();
usingMenu = false;
return;
}
if( selectedAction == a5 ){
tempCut.clear();
tempCutID ++;
isDrawCut= true;
usingMenu = false;
numCut ++;
return;
}
if( selectedAction == a6){
@ -504,6 +508,55 @@ inline void Histogram2D::rightMouseClickMenu(QMouseEvent * event){
replot();
}
if( selectedAction == a8 ){ // load Cuts
QString filePath = QFileDialog::getOpenFileName(this,
"Load Cuts from File",
settingPath,
"Text file (*.txt)");
if (!filePath.isEmpty()) LoadCuts(filePath);
}
//*==================================== when there are cuts
if( selectedAction == b0 ){ // Save Cuts
QString filePath = QFileDialog::getSaveFileName(this,
"Save Cuts to File",
settingPath,
"Text file (*.txt)");
if (!filePath.isEmpty()) SaveCuts(filePath);
}
if( selectedAction == b1 ){
ClearAllCuts();
}
if( selectedAction == b2 ){
QDialog dialog(this);
dialog.setWindowTitle("Add/Edit name of cuts ");
QFormLayout layout(&dialog);
for(int i = 0; i < cutTextIDList.count(); i++){
if( cutTextIDList[i] < 0 ) continue;
QLineEdit * le = new QLineEdit(&dialog);
layout.addRow(colorCycle[i%colorCycle.count()].second, le);
le->setText( cutNameList[i] );
connect(le, &QLineEdit::textChanged, this, [=](){
le->setStyleSheet("color : blue;");
});
connect(le, &QLineEdit::returnPressed, this, [=](){
le->setStyleSheet("");
cutNameList[i] = le->text();
((QCPItemText *) this->item(cutTextIDList[i]))->setText(le->text());
replot();
});
}
dialog.exec();
}
if( selectedAction && numCut > 0 && selectedAction->text().contains("Delete ") ){
QString haha = selectedAction->text();
@ -538,40 +591,11 @@ inline void Histogram2D::rightMouseClickMenu(QMouseEvent * event){
cutNameList.clear();
cutEntryList.clear();
}
return;
}
if( selectedAction && numCut > 0 && selectedAction->text().contains("Clear all Cuts") ){
ClearAllCuts();
return;
}
if( selectedAction && numCut > 0 && selectedAction->text().contains("Add/Edit names to Cuts") ){
QDialog dialog(this);
dialog.setWindowTitle("Add/Edit name of cuts ");
QFormLayout layout(&dialog);
for(int i = 0; i < cutTextIDList.count(); i++){
if( cutTextIDList[i] < 0 ) continue;
QLineEdit * le = new QLineEdit(&dialog);
layout.addRow(colorCycle[i%colorCycle.count()].second, le);
le->setText( cutNameList[i] );
connect(le, &QLineEdit::textChanged, this, [=](){
le->setStyleSheet("color : blue;");
});
connect(le, &QLineEdit::returnPressed, this, [=](){
le->setStyleSheet("");
cutNameList[i] = le->text();
((QCPItemText *) this->item(cutTextIDList[i]))->setText(le->text());
replot();
});
}
dialog.exec();
return;
}
usingMenu = false;
}
@ -593,7 +617,7 @@ inline void Histogram2D::rightMouseClickRebin(){
lineEditX[i] = new QLineEdit(&dialog);
layout.addRow(nameListX[i] + " : ", lineEditX[i]);
}
lineEditX[0]->setText(QString::number(xBin));
lineEditX[0]->setText(QString::number(xBin-2));
lineEditX[1]->setText(QString::number(xMin));
lineEditX[2]->setText(QString::number(xMax));
@ -603,7 +627,7 @@ inline void Histogram2D::rightMouseClickRebin(){
lineEditY[i] = new QLineEdit(&dialog);
layout.addRow(nameListY[i] + " : ", lineEditY[i]);
}
lineEditY[0]->setText(QString::number(yBin));
lineEditY[0]->setText(QString::number(yBin-2));
lineEditY[1]->setText(QString::number(yMin));
lineEditY[2]->setText(QString::number(yMax));
@ -666,12 +690,121 @@ inline void Histogram2D::rightMouseClickRebin(){
if( dialog.exec() == QDialog::Accepted ){
isBusy = true;
Rebin((int)number[0][0], number[1][0], number[2][0], (int)number[0][1], number[1][1], number[2][1]);
rescaleAxes();
UpdatePlot();
isBusy = false;
}
}
inline void Histogram2D::SaveCuts(QString cutFileName){
QFile file(cutFileName);
if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
QTextStream out(&file);
// Define the text to write
QStringList lines;
for( int i = 0; i < cutList.size(); i++){
lines << "====== "+ cutNameList[i];
for( int pt = 0 ; pt < cutList[i].size(); pt ++){
lines << QString::number(cutList[i][pt].rx(), 'g', 5) + "," + QString::number(cutList[i][pt].ry(), 'g', 5);
}
}
lines << "#===== End of File";
// Write each line to the file
for (const QString &line : lines) out << line << "\n";
// Close the file
file.close();
qDebug() << "File written successfully to" << cutFileName;
}else{
qWarning() << "Unable to open file" << cutFileName;
}
}
inline void Histogram2D::LoadCuts(QString cutFileName){
QFile file(cutFileName);
QString cutNameTemp;
// Open the file in read mode
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QTextStream in(&file);
ClearAllCuts();
tempCut.clear();
// Read each line and append to the QStringList
while (!in.atEnd()) {
QString line = in.readLine();
if( line.contains("======") ){
if( !tempCut.isEmpty() ) {
DrawCut();
plottableIDList.push_back(plottableCount() -1 );
cutNameList.push_back(cutNameTemp);
cutEntryList.push_back(0);
QCPItemText * text = new QCPItemText(this);
text->setText(cutNameList.last());
text->position->setCoords(tempCut[0].rx(), tempCut[0].ry());
int colorID = tempCutID% colorCycle.count();
text->setColor(colorCycle[colorID].first);
cutTextIDList.push_back(itemCount() - 1);
cutList.push_back(tempCut);
cutIDList.push_back(tempCutID);
}
tempCut.clear();
tempCutID ++;
numCut ++;
int spacePos = line.indexOf(' ');
cutNameTemp = line.mid(spacePos + 1);
continue;
}
if( line.contains("#==") ) {
DrawCut();
plottableIDList.push_back(plottableCount() -1 );
cutNameList.push_back(cutNameTemp);
cutEntryList.push_back(0);
QCPItemText * text = new QCPItemText(this);
text->setText(cutNameList.last());
text->position->setCoords(tempCut[0].rx(), tempCut[0].ry());
int colorID = tempCutID% colorCycle.count();
text->setColor(colorCycle[colorID].first);
cutTextIDList.push_back(itemCount() - 1);
cutList.push_back(tempCut);
cutIDList.push_back(tempCutID);
break;
}else{
QStringList haha = line.split(",");
// qDebug() << haha;
if( haha.size() == 2 ){
tempCut.push_back(QPointF(haha[0].toFloat(), haha[1].toFloat()));
DrawCut();
}
}
}
// Close the file
file.close();
qDebug() << "File read successfully from" << cutFileName;
qDebug() << " Number of cut loaded " << numCut << ", " << cutList.count();
// PrintCutEntry();
// DrawCut();
replot();
} else {
qWarning() << "Unable to open file" << cutFileName;
}
}
#endif

38
Hit.h
View File

@ -6,7 +6,7 @@
class Hit{
public:
unsigned short sn;
uint8_t ch;
unsigned short ch;
unsigned short energy;
unsigned short energy2;
unsigned long long timestamp;
@ -45,6 +45,42 @@ public:
// Define operator< for sorting
bool operator<(const Hit& other) const {
return timestamp < other.timestamp;
}
void WriteHitsToCAENBinary(FILE * file, uint32_t header){
if( file == nullptr ) return;
uint32_t flag = 0;
uint8_t waveFormCode = 1; // input
// uint16_t header = 0xCAE1; // default to have the energy only
// if( energy2 > 0 ) header += 0x4;
// if( traceLength > 0 && withTrace ) header += 0x8;
size_t dummy;
dummy = fwrite(&sn, 2, 1, file);
dummy = fwrite(&ch, 2, 1, file);
uint64_t timestampPS = timestamp * 1000 + fineTime;
dummy = fwrite(&timestampPS, 8, 1, file);
dummy = fwrite(&energy, 2, 1, file);
if( (header & 0x4) ) dummy = fwrite(&energy2, 2, 1, file);
dummy = fwrite(&flag, 4, 1, file);
if( traceLength > 0 && (header & 0x8) ){
dummy = fwrite(&waveFormCode, 1, 1, file);
dummy = fwrite(&traceLength, 4, 1, file);
for( int j = 0; j < traceLength; j++ ){
dummy = fwrite(&(trace[j]), 2, 1, file);
}
}
if( dummy != 1 ) printf("write file error.\n");
}
};

674
LICENSE Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@ -7,15 +7,18 @@ MultiBuilder::MultiBuilder(Data ** multiData, std::vector<int> type, std::vector
data = multiData;
typeList = type;
snList = sn;
numTotCh = 0;
for( uShort i = 0; i < nData; i++) {
idList.push_back(i);
dataSize.push_back(data[i]->GetDataSize());
numTotCh += data[i]->GetNChannel();
}
timeWindow = 100;
leftOverTime = 100;
breakTime = -1;
timeJump = 1e8;
lastEventTime = 0;
forceStop = false;
ClearEvents();
@ -29,6 +32,7 @@ MultiBuilder::MultiBuilder(Data * singleData, int type, int sn): nData(1){
DebugPrint("%s", "MultiBuilder");
data = new Data *[1];
data[0] = singleData;
numTotCh = data[0]->GetNChannel();
typeList.push_back(type);
snList.push_back(sn);
idList.push_back(0);
@ -37,7 +41,7 @@ MultiBuilder::MultiBuilder(Data * singleData, int type, int sn): nData(1){
breakTime = -1;
timeJump = 1e8;
lastEventTime = 0;
forceStop = false;
ClearEvents();
}
@ -54,9 +58,9 @@ void MultiBuilder::ClearEvents(){
for( int i = 0; i < MaxNDigitizer; i++){
for( int j = 0; j < MaxNChannels; j++){
loopIndex[i][j] = 0;
nextIndex[i][j] = -1;
chExhaused[i][j] = false;
lastBackWardIndex[i][j] = 0;
}
earlistDigi = -1;
@ -74,10 +78,9 @@ void MultiBuilder::PrintStat(){
printf("Total number of evet built : %ld\n", totalEventBuilt);
for( int i = 0; i < nData ; i++){
for( int ch = 0; ch < data[i]->GetNChannel() ; ch++){
if( nextIndex[i][ch] >= 0 ) printf("%d %3d %2d | %7d (%d)\n", i, snList[i], ch, nextIndex[i][ch], loopIndex[i][ch]);
if( nextIndex[i][ch] >= 0 ) printf("%d %3d %2d | %7ld\n", i, snList[i], ch, nextIndex[i][ch]);
}
}
}
void MultiBuilder::PrintAllEvent(){
@ -89,9 +92,10 @@ void MultiBuilder::PrintAllEvent(){
events[i][j].Print();
}
}
}
//^############################################### forward event builder
void MultiBuilder::FindEarlistTimeAndCh(bool verbose){
DebugPrint("%s", "MultiBuilder");
earlistTime = -1;
@ -104,18 +108,19 @@ void MultiBuilder::FindEarlistTimeAndCh(bool verbose){
for(unsigned int ch = 0; ch < data[i]->GetNChannel(); ch ++){
int index = data[i]->GetDataIndex(ch);
if( ch >= data[i]->GetNChannel() || index < 0 ) {
nExhaushedCh ++;
chExhaused[i][ch] = true;
continue;
}
{// check is dataIndex is valid
int index = data[i]->GetDataIndex(ch);
if( index < 0 ) {
nExhaushedCh ++;
chExhaused[i][ch] = true;
continue;
}
if( data[i]->GetTimestamp(ch, index) == 0 ||
loopIndex[i][ch] * dataSize[i] > data[i]->GetLoopIndex(ch) * dataSize[i] + data[i]->GetDataIndex(ch)) {
nExhaushedCh ++;
chExhaused[i][ch] = true;
continue;
if( data[i]->GetTimestamp(ch, index) == 0 || nextIndex[i][ch] > data[i]->GetAbsDataIndex(ch)) {
nExhaushedCh ++;
chExhaused[i][ch] = true;
continue;
}
}
if( nextIndex[i][ch] == -1 ) nextIndex[i][ch] = 0;
@ -126,46 +131,11 @@ void MultiBuilder::FindEarlistTimeAndCh(bool verbose){
earlistDigi = i;
earlistCh = ch;
}
// printf(" ch : %d | time %llu | %llu\n", ch, time, earlistTime);
}
}
if( verbose ) printf("%s | bd : %d, ch : %d, %llu\n", __func__, earlistDigi, earlistCh, earlistTime);
}
void MultiBuilder::FindLatestTimeAndCh(bool verbose){
DebugPrint("%s", "MultiBuilder");
latestTime = 0;
latestDigi = -1;
latestCh = -1;
nExhaushedCh = 0;
for( int i = 0; i < nData; i++){
for( int j = 0; j < data[i]->GetNChannel(); j++ ) chExhaused[i][j] = false;
for(unsigned int ch = 0; ch < MaxNChannels; ch ++){
if( nextIndex[i][ch] < 0 || ch >= data[i]->GetNChannel() || data[i]->GetDataIndex(ch) < 0 ) {
nExhaushedCh ++;
chExhaused[i][ch] = true;
// printf(", exhanshed. %d \n", nExhaushedCh);
continue;
}
unsigned long long time = data[i]->GetTimestamp(ch, nextIndex[i][ch]);
// printf(", time : %llu\n", time );
if( time > latestTime ) {
latestTime = time;
latestDigi = i;
latestCh = ch;
}
}
}
if( verbose ) printf("%s | bd : %d, ch : %d, %llu\n", __func__, latestDigi, latestCh, latestTime);
}
void MultiBuilder::FindEarlistTimeAmongLastData(bool verbose){
@ -187,6 +157,187 @@ void MultiBuilder::FindEarlistTimeAmongLastData(bool verbose){
}
if( verbose ) printf("%s | bd : %d, ch : %d, %lld \n", __func__, latestDigi, latestCh, latestTime);
}
void MultiBuilder::BuildEvents(bool isFinal, bool skipTrace, bool verbose){
DebugPrint("%s", "MultiBuilder");
FindEarlistTimeAndCh(verbose); //Give the earliest time, ch, digi
FindEarlistTimeAmongLastData(verbose); // give lastest Time, Ch, and Digi for event building
if( earlistCh == -1 || nExhaushedCh == numTotCh) return; /// no data
eventBuilt = 0;
//======= Start building event
Hit em;
do{
if( forceStop ) break;
eventIndex ++;
if( eventIndex >= MaxNEvent ) eventIndex = 0;
events[eventIndex].clear();
em.Clear();
for( int k = 0; k < nData; k++){
int bd = (k + earlistDigi) % nData;
// printf("##### %d/%d | ", bd, nData);
// data[bd]->PrintAllData(true);
const int numCh = data[bd]->GetNChannel();
for( int i = 0; i < numCh; i++){
int ch = (i + earlistCh ) % numCh;
// printf("ch : %d | exhaused ? %s \n", ch, chExhaused[bd][ch] ? "Yes" : "No");
if( chExhaused[bd][ch] ) continue;
// printf(" ch : %2d | %d(%d) | %d(%d)\n", ch, loopIndex[bd][ch], nextIndex[bd][ch], data[bd]->GetLoopIndex(ch), data[bd]->GetDataIndex(ch) );
if( nextIndex[bd][ch] == -1 || nextIndex[bd][ch] > data[bd]->GetAbsDataIndex(ch)) {
nExhaushedCh ++;
chExhaused[bd][ch] = true;
// printf(" ch : %d exhaused\n", ch);
continue;
}
do {
unsigned long long time = data[bd]->GetTimestamp(ch, nextIndex[bd][ch]);
// printf("%6d, sn: %5d, ch: %2d, timestamp : %16llu | earlistTime : %16llu | timeWindow : %u \n", nextIndex[bd][ch], data[bd]->boardSN, ch, time, earlistTime, timeWindow);
if( time >= earlistTime && (time - earlistTime <= timeWindow) ){
em.sn = snList[bd];
em.ch = ch;
em.energy = data[bd]->GetEnergy(ch, nextIndex[bd][ch]);
em.timestamp = time;
em.fineTime = data[bd]->GetFineTime(ch, nextIndex[bd][ch]);
if( !skipTrace ) em.trace = data[bd]->Waveform1[ch][nextIndex[bd][ch]];
if( typeList[bd] == DPPTypeCode::DPP_PSD_CODE ) em.energy2 = data[bd]->GetEnergy2(ch, nextIndex[bd][ch]);
events[eventIndex].push_back(em);
nextIndex[bd][ch]++;
}else{
break;
}
if( timeWindow == 0 ) break;
}while( true );
if( timeWindow == 0 ) break;
}
if( timeWindow == 0 ) break;
}
if( events[eventIndex].size() == 0 ) {
if( eventIndex > 1) {
eventIndex --;
}else{
eventIndex = MaxNEvent - 1;
}
continue;
}
if( events[eventIndex].size() > 1) {
std::sort(events[eventIndex].begin(), events[eventIndex].end(), [](const Hit& a, const Hit& b) {
return a.timestamp < b.timestamp;
});
}
// lastEventTime = events[eventIndex].back().timestamp;
///Find the next earlist
FindEarlistTimeAndCh(false);
// //if there is a time jump, say, bigger than TimeJump. break
// if( earlistTime - lastEventTime > timeJump ) {
// if( verbose ){
// printf("!!!!!!!! Time Jump detected stop event building and get more data.\n");
// printf("event index : %6lu, last event time : %16llu\n", eventIndex, lastEventTime);
// printf(" %6s earilest time : %16llu \n", "", earlistTime);
// printf(" %6s time jump > %16llu \n", "", timeJump);
// }
// return;
// }
eventBuilt ++;
totalEventBuilt ++;
if( verbose ){
printf(">>>>>>>>>>>>>>>>> Event ID : %ld, total built: %ld, multiplicity : %ld\n", eventIndex, totalEventBuilt, events[eventIndex].size());
for( int i = 0; i <(int) events[eventIndex].size(); i++){
int chxxx = events[eventIndex][i].ch;
int sn = events[eventIndex][i].sn;
int bd = 0;
for( int pp = 0; pp < nData; pp++){
if( sn == data[pp]->boardSN ) {
bd = pp;
break;
}
}
printf("%05d, %02d | %7ld | %5d %llu \n", sn, chxxx, nextIndex[bd][chxxx], events[eventIndex][i].energy, events[eventIndex][i].timestamp);
}
if( nExhaushedCh == numTotCh ) {
printf("######################### no more event to be built\n");
break;
}
printf("----- next bd : %d, ch : %d, next earlist Time : %llu.\n", earlistDigi, earlistCh, earlistTime);
//printf("leftOver %llu, breakTime %llu \n", leftOverTime, breakTime);
}
if( !isFinal ){
if( latestTime - earlistTime <= leftOverTime){
if( verbose ) printf("######################### left over data for next build, latesTime : %llu. | leftOverTime : %llu\n", latestTime, leftOverTime);
break;
}
if( earlistTime > breakTime ) {
if( verbose ) printf("######################### left over data for next build, earlistTime : %llu. | breakTime : %llu\n", earlistTime, breakTime);
break;
}
}
}while(nExhaushedCh < numTotCh);
forceStop = false;
}
//^############################################### backward event builder
void MultiBuilder::FindLatestTimeAndCh(bool verbose){
DebugPrint("%s", "MultiBuilder");
latestTime = 0;
latestDigi = -1;
latestCh = -1;
nExhaushedCh = 0;
for( int i = 0; i < nData; i++){
for( int j = 0; j < data[i]->GetNChannel(); j++ ) chExhaused[i][j] = false;
for(unsigned int ch = 0; ch < data[i]->GetNChannel(); ch ++){
if( nextIndex[i][ch] < 0 || data[i]->GetDataIndex(ch) < 0 || nextIndex[i][ch] <= lastBackWardIndex[i][ch] ) {
nExhaushedCh ++;
chExhaused[i][ch] = true;
// printf(", exhanshed. %d \n", nExhaushedCh);
continue;
}
unsigned long long time = data[i]->GetTimestamp(ch, nextIndex[i][ch]);
// printf(", time : %llu\n", time );
if( time > latestTime ) {
latestTime = time;
latestDigi = i;
latestCh = ch;
}
}
}
if( verbose ) printf("%s | bd : %d, ch : %d, %llu\n", __func__, latestDigi, latestCh, latestTime);
}
void MultiBuilder::FindLatestTimeOfData(bool verbose){
DebugPrint("%s", "MultiBuilder");
@ -209,145 +360,15 @@ void MultiBuilder::FindLatestTimeOfData(bool verbose){
if( verbose ) printf("%s | bd : %d, ch : %d, %lld \n", __func__, latestDigi, latestCh, latestTime);
}
void MultiBuilder::BuildEvents(bool isFinal, bool skipTrace, bool verbose){
DebugPrint("%s", "MultiBuilder");
FindEarlistTimeAmongLastData(verbose); // give lastest Time, Ch, and Digi
FindEarlistTimeAndCh(verbose); //Give the earliest time, ch, digi
if( earlistCh == -1 || nExhaushedCh == nData * MaxNChannels) return; /// no data
eventBuilt = 0;
//======= Start building event
Hit em;
do{
eventIndex ++;
if( eventIndex >= MaxNEvent ) eventIndex = 0;
events[eventIndex].clear();
eventBuilt ++;
totalEventBuilt ++;
em.Clear();
for( int k = 0; k < nData; k++){
int bd = (k + earlistDigi) % nData;
// printf("##### %d/%d | ", k, nData);
// data[k]->PrintAllData(true, 10);
const int numCh = data[bd]->GetNChannel();
for( int i = 0; i < numCh; i++){
int ch = (i + earlistCh ) % numCh;
// printf("ch : %d | exhaused ? %s \n", ch, chExhaused[bd][ch] ? "Yes" : "No");
if( chExhaused[bd][ch] ) continue;
if( loopIndex[bd][ch] * dataSize[bd] + nextIndex[bd][ch] > data[bd]->GetLoopIndex(ch) * dataSize[bd] + data[bd]->GetDataIndex(ch)) {
nExhaushedCh ++;
chExhaused[bd][ch] = true;
continue;
}
do {
unsigned long long time = data[bd]->GetTimestamp(ch, nextIndex[bd][ch]);
//printf("%6ld, sn: %5d, ch: %2d, timestamp : %16llu | earlistTime : %16llu | timeWindow : %u \n", eventIndex, data[bd]->boardSN, ch, time, earlistTime, timeWindow);
if( time >= earlistTime && (time - earlistTime <= timeWindow) ){
em.sn = snList[bd];
em.ch = ch;
em.energy = data[bd]->GetEnergy(ch, nextIndex[bd][ch]);
em.timestamp = time;
em.fineTime = data[bd]->GetFineTime(ch, nextIndex[bd][ch]);
if( !skipTrace ) em.trace = data[bd]->Waveform1[ch][nextIndex[bd][ch]];
if( typeList[bd] == DPPTypeCode::DPP_PSD_CODE ) em.energy2 = data[bd]->GetEnergy2(ch, nextIndex[bd][ch]);
events[eventIndex].push_back(em);
nextIndex[bd][ch]++;
if( nextIndex[bd][ch] >= dataSize[bd]) {
loopIndex[bd][ch] ++;
nextIndex[bd][ch] = 0;
}
}else{
break;
}
if( timeWindow <= 0 ) break;
}while( true );
if( timeWindow <= 0 ) break;
}
if( timeWindow <= 0 ) break;
}
if( events[eventIndex].size() > 1) {
std::sort(events[eventIndex].begin(), events[eventIndex].end(), [](const Hit& a, const Hit& b) {
return a.timestamp < b.timestamp;
});
}
lastEventTime = events[eventIndex].back().timestamp;
///Find the next earlist
FindEarlistTimeAndCh(false);
// //if there is a time jump, say, bigger than TimeJump. break
if( earlistTime - lastEventTime > timeJump ) {
if( verbose ){
printf("%6lu, %16llu\n", eventIndex, earlistTime);
printf("%5s - %16llu \n", "", lastEventTime);
printf("%5s > %16llu \n", "", timeJump);
printf("!!!!!!!! Time Jump detected stop event building. stop event buinding and get more data.\n");
}
return;
}
if( verbose ){
printf(">>>>>>>>>>>>>>>>> Event ID : %ld, total built: %ld, multiplicity : %ld\n", eventIndex, totalEventBuilt, events[eventIndex].size());
for( int i = 0; i <(int) events[eventIndex].size(); i++){
int chxxx = events[eventIndex][i].ch;
int sn = events[eventIndex][i].sn;
int bd = 0;
for( int pp = 0; pp < nData; pp++){
if( sn == data[pp]->boardSN ) {
bd = pp;
break;
}
}
printf("%05d, %02d | %5d | %5d %llu \n", sn, chxxx, nextIndex[bd][chxxx], events[eventIndex][i].energy, events[eventIndex][i].timestamp);
}
if( nExhaushedCh == nData * MaxNChannels ) {
printf("######################### no more event to be built\n");
break;
}
printf("----- next bd : %d, ch : %d, next earlist Time : %llu.\n", earlistDigi, earlistCh, earlistTime);
//printf("leftOver %llu, breakTime %llu \n", leftOverTime, breakTime);
}
if( !isFinal ){
if( latestTime - earlistTime <= leftOverTime){
if( verbose ) printf("######################### left over data for next build, latesTime : %llu. | leftOverTime : %llu\n", latestTime, leftOverTime);
break;
}
if( earlistTime > breakTime ) {
if( verbose ) printf("######################### left over data for next build, earlistTime : %llu. | breakTime : %llu\n", earlistTime, breakTime);
break;
}
}
}while(nExhaushedCh < nData * MaxNChannels);
}
void MultiBuilder::BuildEventsBackWard(int maxNumEvent, bool verbose){
DebugPrint("%s", "MultiBuilder");
//skip trace, and only build for maxNumEvent events max
// remember the end of DataIndex, prevent over build
// Get the last data index and loop index
for( int k = 0; k < nData; k++){
for( int i = 0; i < data[k]->GetNChannel(); i++){
nextIndex[k][i] = data[k]->GetDataIndex(i);
loopIndex[k][i] = data[k]->GetLoopIndex(i);
nextIndex[k][i] = data[k]->GetAbsDataIndex(i);
}
}
@ -357,12 +378,11 @@ void MultiBuilder::BuildEventsBackWard(int maxNumEvent, bool verbose){
eventBuilt = 0;
Hit em;
do{
if( forceStop ) break;
eventIndex ++;
if( eventIndex >= MaxNEvent ) eventIndex = 0;
events[eventIndex].clear();
eventBuilt ++;
totalEventBuilt ++;
em.Clear();
for( int k = 0; k < nData; k++){
@ -373,10 +393,9 @@ void MultiBuilder::BuildEventsBackWard(int maxNumEvent, bool verbose){
for( int i = 0; i < numCh; i++){
int ch = (i + latestCh) % numCh;
if( chExhaused[bd][ch] ) continue;
//if( nextIndex[bd][ch] <= lastBackWardIndex[bd][ch] || nextIndex[bd][ch] < 0){
if( nextIndex[bd][ch] < 0){
chExhaused[bd][ch] = true;
if( nextIndex[bd][ch] <= lastBackWardIndex[bd][ch] || nextIndex[bd][ch] <= 0){
nExhaushedCh ++;
chExhaused[bd][ch] = true;
continue;
}
@ -392,7 +411,7 @@ void MultiBuilder::BuildEventsBackWard(int maxNumEvent, bool verbose){
events[eventIndex].push_back(em);
nextIndex[bd][ch]--;
if( nextIndex[bd][ch] < 0 && data[bd]->GetLoopIndex(ch) > 0 ) nextIndex[bd][ch] = dataSize[bd] - 1;
// if( nextIndex[bd][ch] < 0 && data[bd]->GetLoopIndex(ch) > 0 ) nextIndex[bd][ch] = dataSize[bd] - 1;
}else{
break;
@ -404,12 +423,27 @@ void MultiBuilder::BuildEventsBackWard(int maxNumEvent, bool verbose){
if( timeWindow == 0 ) break;
}
std::sort(events[eventIndex].begin(), events[eventIndex].end(), [](const Hit& a, const Hit& b) {
return a.timestamp < b.timestamp;
});
FindLatestTimeAndCh(verbose);
if( verbose ) printf(" nExhaushedCh %d | numToCh %d \n", nExhaushedCh, numTotCh);
if( nExhaushedCh == numTotCh ) {
if( verbose ) printf("######################### no more event to be built\n");
break;
}
if( verbose ) printf("----- next bd: %d, ch : %d, next latest Time : %llu.\n", latestDigi, latestCh, latestTime);
if( events[eventIndex].size() > 0 ) {
eventBuilt ++;
totalEventBuilt ++;
std::sort(events[eventIndex].begin(), events[eventIndex].end(), [](const Hit& a, const Hit& b) {
return a.timestamp < b.timestamp;
});
}else{
continue;
}
if( verbose ){
printf(">>>>>>>>>>>>>>>>> Event ID : %ld, total built: %ld, multiplicity : %ld\n", eventIndex, totalEventBuilt, events[eventIndex].size());
for( int i = 0; i <(int) events[eventIndex].size(); i++){
@ -422,24 +456,19 @@ void MultiBuilder::BuildEventsBackWard(int maxNumEvent, bool verbose){
break;
}
}
printf("%05d, %02d | %5d | %5d %llu \n", sn, chxxx, nextIndex[bd][chxxx], events[eventIndex][i].energy, events[eventIndex][i].timestamp);
printf("%5d, %02d | %7ld | %5d %llu \n", sn, chxxx, nextIndex[bd][chxxx], events[eventIndex][i].energy, events[eventIndex][i].timestamp);
}
if( nExhaushedCh == nData * MaxNChannels ) {
printf("######################### no more event to be built\n");
break;
}
printf("----- next bd: %d, ch : %d, next latest Time : %llu.\n", latestDigi, latestCh, latestTime);
}
}while(nExhaushedCh < nData * MaxNChannels && eventBuilt < maxNumEvent);
}while(nExhaushedCh < numTotCh && eventBuilt < maxNumEvent);
// // remember the end of DataIndex, prevent over build
// for( int k = 0; k < nData; k++){
// for( int i = 0; i < MaxRegChannel; i++){
// lastBackWardIndex[k][i] = data[k]->DataIndex[i];
// }
// }
forceStop = false;
// remember the end of DataIndex, prevent over build
for( int k = 0; k < nData; k++){
for( int i = 0; i < data[k]->GetNChannel(); i++){
lastBackWardIndex[k][i] = data[k]->GetAbsDataIndex(i);
}
}
}

View File

@ -14,16 +14,18 @@ public:
MultiBuilder(Data * singleData, int type, int sn);
~MultiBuilder();
void SetTimeWindow(unsigned short ticks) {timeWindow = ticks; leftOverTime = ticks;}
void ForceStop(bool onOff) { forceStop = onOff;}
void SetTimeWindow(unsigned short nanosec) {timeWindow = nanosec; leftOverTime = nanosec;}
unsigned short GetTimeWindow() const{return timeWindow;}
void SetTimeJump(unsigned long long TimeJumpInNanoSec) {timeJump = TimeJumpInNanoSec;}
unsigned long long GetTimeJump() const {return timeJump;}
void SetLeftOverTime(unsigned long long ticks) {leftOverTime = ticks;}
void SetLeftOverTime(unsigned long long nanosec) {leftOverTime = nanosec;}
unsigned long long GetLeftOverTime() const{return leftOverTime;}
void SetBreakTime(unsigned long long ticks) {breakTime = ticks;}
void SetBreakTime(unsigned long long nanosec) {breakTime = nanosec;}
unsigned long long GetBreakTime() const{return breakTime;}
unsigned int GetNumOfDigitizer() const {return nData;}
@ -48,6 +50,7 @@ private:
std::vector<int> tick2ns;
const unsigned short nData;
Data ** data; // assume all data has MaxNChannel (16)
int numTotCh; // number of total channel = sum digi[i]->GetNChannel()
std::vector<uShort> dataSize;
@ -58,8 +61,8 @@ private:
unsigned long long timeJump; //time diff for a time jump, default is 1e8 ns
unsigned long long lastEventTime; // timestamp for detect time jump
int loopIndex[MaxNDigitizer][MaxNChannels];
int nextIndex[MaxNDigitizer][MaxNChannels];
// int loopIndex[MaxNDigitizer][MaxNChannels];
long nextIndex[MaxNDigitizer][MaxNChannels]; // loopIndex * dataSize + index
int nExhaushedCh;
bool chExhaused[MaxNDigitizer][MaxNChannels];
@ -76,7 +79,9 @@ private:
void FindEarlistTimeAmongLastData(bool verbose = false);
void FindLatestTimeOfData(bool verbose = false);
int lastBackWardIndex[MaxNDigitizer][MaxNChannels];
int lastBackWardIndex[MaxNDigitizer][MaxNChannels]; // abs. index
bool forceStop;
};

View File

@ -6,19 +6,19 @@ https://discord.gg/xVsRhNZF8G
This is a DAQ for 1st gen CAEN digitizer for
- V1725, V17255S, V1230 with PHA and PSD firmware.
- x725, x725S, x730 with PHA and PSD firmware.
- V1740 with QDC firmware
It has scope (updated every half-sec), allow full control of the digitizer (except LVDS), and allow saving waveform.
It can be connected to InfluxDB v1.8+ and Elog.
Each channel has it own 1D histogram. It will not be filled by default, but can enable it in the "Online 1D histgram" panel. The binning of each histogram will be saved under the raw data path as singleSpectaSetting.txt
Each channel has it own 1D histogram. It will not be filled by default, but can enable it in the "Online Histgrams" panel. The binning of each histogram will be saved under the raw data path as singleSpectaSetting.txt
## Wiki
https://fsunuc.physics.fsu.edu/wiki/index.php/CAEN_digitizer
## Online analyzer
# Online analyzer
A Multi-builder (event builder that can build event across multiple digitizer) is made. It has normal event building code and also a backward event building code that build events from the latest data up to certain amont of event.
A 1-D and 2-D histogram is avalible. In the 2-D histogram, graphical cuts can be created and rename.
@ -27,6 +27,25 @@ An online analyzer class is created as a template for online analysis. An exampl
<span style="color:red;">Notice that, when the FSUDAQ is started, the online analyzer is not created, no event will be built. Once the online anlyzer is created and opened, event will be built, even the window is closed. </span>
## Create a custom online analyzer
Under the analyzer folder, there are few examples can be followed. Teh idea is create a derivative class based on the Analyzer.h. To implement the new online analyzer, user need to modify a few things:
- add the code file into FSUDAQ_At.pro
- add the header to the top of FSUDAQ.cpp
- edit the vector onlienAnalyzerList at th etop of FSUDAQ.cpp
- edit the FSUDAQ::OpenAnalyzer()
after that, we need to update the makefile by
```sh
>qmake6 FSUDAQ_Qt6.pro
```
and then recompile by
```sh
>make
```
# Operation
When programSettings.txt is presented in the same folder as the FSUDAQ_Qt, the program will load it can config the following
@ -65,8 +84,7 @@ User must setup the data path for data take. Without the data path, user still c
# ToDo
- Gaussians fitting for 1D Histogram
- Improve the color scheme for 2D histogram
- Gaussians fitting for 1D Histogra
- Save Histogram?
# Required / Development enviroment
@ -77,6 +95,7 @@ Ubuntu 22.04
- CAENCOmm v1.5.3 +
- CAENDigitizer v2.17.1 +
- CAEN A3818 Driver v1.6.8 +
- CAENUSBdrv v1.5.5 + (for V57XX digitizer with USB connection)
- qt6-base-dev
- libqt6charts6-dec
@ -135,13 +154,28 @@ if you want to use GDB debugger, in the *.pro file add
` QMAKE_CXXFLAGS += -g`
# Auxillary programs (e.g. Event Builder)
There is a folder Aux, this folder contains many auxillary programs, such as EventBuilder. User can `make` under the folder to compile the programs.
# Tested Trigger Rate
# Enable Core dump
The program has abort handler to save core dump.
first, enable the gdb in compilation by edit the FSUDAQ_Qt6.pro by commen out the following lines:
```sh
QMAKE_CXXFLAGS += -g
QMAKE_CXXFLAGS_RELEASE = -O0
QMAKE_CFLAGS_RELEASE = -O0
```
second, ensure the core dump file has unlimited size and set the core dump file name
```sh
>ulimit -c unlimited
>echo "core.%e.%p" | sudo tee /proc/sys/kernel/core_pattern
```
* V1725, 1 MHz to 3 ch (decay = 500 ns), no trace. need to set Agg/Read = 100 and Evt/Agg = 511.
# Known Issues
@ -150,10 +184,11 @@ There is a folder Aux, this folder contains many auxillary programs, such as Eve
* When using the scope, the Agg/Read must be smaller than 512.
* Although the Events/Agg used the CAEN API to recalculate before ACQ start, for PHA firmware, when the trigger rate changed, the Events per Agg need to be changed.
* The Agg Organization, Event per Agg, Record Length are strongly correlated. Some settings are invalid and will cause the digitizer goes crazy.
* load digitizer setting would not load everything, only load the channel settings and some board settings.
* Load digitizer setting would not load everything, only load the channel settings and some board settings.
* Sometimes, the buffer is not in time order, and make the trigger/Accept rate to be nagative. This is nothing to do with the program but the digitizer settings. Recommand reporgram the digitizer.
* for 1740 QDC, RecordLenght is board setting, but readout is indivuial group.
* FOr PHA, the trapezoid scaling and fine-gain register are calculated before ACQ start.
* For 1740 QDC, RecordLenght is board setting, but readout is indivuial group.
* For PHA, the trapezoid scaling and fine-gain register are calculated before ACQ start.
* For 1740D QDC, when 1st grouped channel is enabled, the 0th-channel must be enabled, otherwise, there is a ReadData error and the ACQ will stop.
# Known Bugs

View File

@ -171,7 +171,7 @@ const Reg FrontPanelTRGOUTEnableMask ("FrontPanelTRGOUTEnableMask" , 0x8110,
const Reg PostTrigger ("PostTrigger" , 0x8114, RW::ReadWrite, false, {}); /// R/W
const Reg LVDSIOData ("LVDSIOData" , 0x8118, RW::ReadWrite, false, {}); /// R/W
const Reg FrontPanelIOControl ("FrontPanelIOControl" , 0x811C, RW::ReadWrite, false, {}); /// R/W
const Reg RegChannelEnableMask ("RegChannelEnableMask" , 0x8120, RW::ReadWrite, false, {}); /// R/W
const Reg RegChannelEnableMask ("RegChannelEnableMask" , 0x8120, RW::ReadWrite, false, {}); /// R/W
const Reg ROCFPGAFirmwareRevision_R ("ROCFPGAFirmwareRevision_R" , 0x8124, RW::ReadONLY , false, {}); /// R
const Reg EventStored_R ("EventStored_R" , 0x812C, RW::ReadONLY , false, {}); /// R
const Reg VoltageLevelModeConfig ("VoltageLevelModeConfig" , 0x8138, RW::ReadWrite, false, {}); /// R/W
@ -199,7 +199,6 @@ const Reg Scratch ("Scratch" , 0xEF20,
const Reg SoftwareReset_W ("SoftwareReset_W" , 0xEF24, RW::WriteONLY, false, {}); /// W
const Reg SoftwareClear_W ("SoftwareClear_W" , 0xEF28, RW::WriteONLY, false, {}); /// W
///====== Common for PHA and PSD
namespace DPP {
@ -315,7 +314,7 @@ namespace DPP {
const std::vector<std::pair<std::string, unsigned int>> ListPolarity = {{"Positive", 0},
{"Negative", 1}};
const std::vector<std::pair<std::string, unsigned int>> ListTrigMode = {{"Independent", 0},
const std::vector<std::pair<std::string, unsigned int>> ListTrigMode = {{"Normal", 0},
{"Coincident", 1},
{"Anti-Coincident", 3}};
@ -382,7 +381,7 @@ namespace DPP {
const std::vector<std::pair<std::string, unsigned int>> ListPolarity = {{"Positive", 0},
{"Negative", 1}};
const std::vector<std::pair<std::string, unsigned int>> ListTrigMode = {{"Independent", 0},
const std::vector<std::pair<std::string, unsigned int>> ListTrigMode = {{"Normal", 0},
{"Coincident ", 1},
{"Anti-Coincident", 3}};
@ -481,7 +480,7 @@ namespace DPP {
{"TTL I/O", 1}};
const std::vector<std::pair<std::string, unsigned int>> ListTRGIMode = {{"Edge of TRG-IN", 0},
{"Whole duration of TRG-IN", 1}};
const std::vector<std::pair<std::string, unsigned int>> ListTRGIMezzanine = {{"Pocessed by Motherboard", 0},
const std::vector<std::pair<std::string, unsigned int>> ListTRGINMezzanine = {{"Pocessed by Motherboard", 0},
{"Skip Motherboard", 1}};
const std::vector<std::pair<std::string, unsigned int>> ListTRGOUTConfig = {{"Disable", 0x00002}, /// this is TRG_OUT high imped. 0x811C bit[1]
@ -509,7 +508,7 @@ namespace DPP {
const Reg RecordLength_G ("RecordLength_G" , 0x1020, RW::ReadWrite, true, 0x3FFF, 8); /// R/W
const Reg InputDynamicRange ("InputDynamicRange" , 0x1028, RW::ReadWrite, false, {{"2 Vpp", 0},{"0.5 Vpp", 1}}); /// R/W
const Reg NumberEventsPerAggregate_G ("NumberEventsPerAggregate_G" , 0x1034, RW::ReadWrite, true, 0x3FF, -1); /// R/W
const Reg NumberEventsPerAggregate_G ("NumberEventsPerAggregate_G" , 0x1034, RW::ReadWrite, true, 0x1FF, -1); /// R/W
const Reg PreTrigger ("PreTrigger" , 0x1038, RW::ReadWrite, false, 0xFF, 4); /// R/W
const Reg TriggerThreshold ("TriggerThreshold" , 0x106C, RW::ReadWrite, false, 0x3FFF, -1); /// R/W
const Reg TriggerHoldOffWidth ("TriggerHoldOffWidth" , 0x1074, RW::ReadWrite, false, 0x3FF, 4); /// R/W
@ -546,7 +545,7 @@ namespace DPP {
const Reg RegChannelEnableMask ("RegChannelEnableMask" , 0x8120, RW::ReadWrite, false, {}); /// R/W
const Reg ROCFPGAFirmwareRevision_R ("ROCFPGAFirmwareRevision_R" , 0x8124, RW::ReadONLY , false, {}); /// R
const Reg EventStored_R ("EventStored_R" , 0x812C, RW::ReadONLY , false, {}); /// R
const Reg VoltageLevelModeConfig ("VoltageLevelModeConfig" , 0x8138, RW::ReadWrite, false, {}); /// R/W
const Reg VoltageLevelModeConfig ("VoltageLevelModeConfig" , 0x8138, RW::ReadWrite, false, 0xFFF, -1); /// R/W
const Reg SoftwareClockSync_W ("SoftwareClockSync_W" , 0x813C, RW::WriteONLY, false, {}); /// W
const Reg BoardInfo_R ("BoardInfo_R" , 0x8140, RW::ReadONLY , false, {}); /// R
const Reg AnalogMonitorMode ("AnalogMonitorMode" , 0x8144, RW::ReadWrite, false, {{"Trig. Maj. Mode", 0},
@ -601,6 +600,9 @@ namespace DPP {
const Reg TriggerValidationMask_G ("TriggerValidationMask_G" , 0x8180, RW::ReadWrite, true, {}); /// R/W,
//& Artifical Register that not in CAEN manual
const Reg DecimationFactor ("Decimation Factor" , 0x8044, RW::ReadWrite, false, 0x7, -1); /// R/W
namespace PHA {
const Reg DataFlush_W ("DataFlush_W" , 0x103C, RW::WriteONLY, false, {}); /// W not sure
const Reg ChannelStopAcquisition ("ChannelStopAcquisition" , 0x1040, RW::ReadWrite, false, {{"Run", 0}, {"Stop", 1}}); /// R/W not sure
@ -645,7 +647,7 @@ namespace DPP {
const std::vector<std::pair<std::string, unsigned int>> ListLocalTrigValidMode = {{"Disabled", 0},
{"Crossed Trigger", 4},
{"Both from Mother board", 5},
{"Both from TRG_VAL", 5},
{"AND", 6},
{"OR", 7}};
@ -734,7 +736,7 @@ namespace DPP {
const std::vector<std::pair<std::string, unsigned int>> ListLocalTrigValidMode = {{"Disabled", 0},
{"Crossed Trigger", 4},
{"Both from Mother board", 5},
{"Both from TRG_VAL", 5},
{"AND", 6},
{"OR", 7}};
@ -793,7 +795,7 @@ namespace DPP {
const Reg DPPAlgorithmControl ("DPPAlgorithmControl" , 0x1040, RW::ReadWrite, false, {}); /// R/W
const Reg TriggerHoldOffWidth ("Trigger Hold-off width" , 0x1074, RW::ReadWrite, false, 0xFFFF, 1); /// R/W
const Reg TRGOUTWidth ("Trigger out width" , 0x1078, RW::ReadWrite, false, 0xFFFF, 1); /// R/W
//const Reg OverThresholdWidth ("Over Threshold width" , 0x107C, RW::ReadWrite, false, 0xFFFF, 1); /// R/W // need firmware version 4.25 & 135.17
const Reg OverThresholdWidth ("Over Threshold width" , 0x107C, RW::ReadWrite, false, 0xFFFF, 1); /// R/W // need firmware version 4.25 & 135.17
const Reg GroupStatus_R ("Group Status" , 0x1088, RW::ReadONLY, false, {}); /// R/
const Reg AMCFirmwareRevision_R ("AMC firmware version" , 0x108C, RW::ReadONLY, false, {}); /// R/
const Reg DCOffset ("DC offset" , 0x1098, RW::ReadWrite, false, 0xFFFF, -1); /// R/W
@ -819,7 +821,7 @@ namespace DPP {
const std::pair<unsigned short, unsigned short> ChargeSensitivity = {3, 0} ; /// length, smallest pos
const std::pair<unsigned short, unsigned short> InternalTestPulse = {1, 4};
const std::pair<unsigned short, unsigned short> TestPulseRate = {2, 5};
//const std::pair<unsigned short, unsigned short> OverThresholdWitdhEnable = {1, 7}; ///need firmware version 4.25 & 135.17
const std::pair<unsigned short, unsigned short> OverThresholdWitdhEnable = {1, 7}; ///need firmware version 4.25 & 135.17
const std::pair<unsigned short, unsigned short> ChargePedestal = {1, 8};
const std::pair<unsigned short, unsigned short> InputSmoothingFactor = {3, 12};
const std::pair<unsigned short, unsigned short> Polarity = {1, 16};
@ -935,7 +937,7 @@ const std::vector<Reg> RegisterChannelList_QDC = {
DPP::QDC::DPPAlgorithmControl,
DPP::QDC::TriggerHoldOffWidth,
DPP::QDC::TRGOUTWidth,
//DPP::QDC::OverThresholdWidth,
DPP::QDC::OverThresholdWidth,
DPP::QDC::GroupStatus_R,
DPP::QDC::AMCFirmwareRevision_R,
DPP::QDC::DCOffset,
@ -1027,6 +1029,7 @@ const std::vector<Reg> RegisterBoardList_QDC = {
DPP::QDC::NumberEventsPerAggregate,
DPP::QDC::RecordLength_W,
DPP::QDC::RecordLength_R,
DPP::DecimationFactor,
DPP::AcquisitionControl,
DPP::AcquisitionStatus_R,
DPP::SoftwareTrigger_W,

143
Scope.cpp
View File

@ -6,6 +6,7 @@
#include <QGroupBox>
#include <QStandardItemModel>
#include <QLabel>
#include <QScreen>
QVector<QPointF> Scope::TrapezoidFilter(QVector<QPointF> data, int baseLineEndS, int riseTimeS, int flatTopS, float decayTime_ns){
DebugPrint("%s", "Scope");
@ -40,12 +41,12 @@ QVector<QPointF> Scope::TrapezoidFilter(QVector<QPointF> data, int baseLineEndS,
trapezoid.append(QPointF(data[i].x(), sn / decayTime_ns / riseTimeS));
}
}
return trapezoid;
}
//^========================================================
//^========================================================
Scope::Scope(Digitizer ** digi, unsigned int nDigi, ReadDataThread ** readDataThread, QMainWindow * parent) : QMainWindow(parent){
DebugPrint("%s", "Scope");
this->digi = digi;
@ -53,9 +54,17 @@ Scope::Scope(Digitizer ** digi, unsigned int nDigi, ReadDataThread ** readDataTh
this->readDataThread = readDataThread;
setWindowTitle("Scope");
setGeometry(0, 0, 1000, 800);
setWindowFlags( this->windowFlags() & ~Qt::WindowCloseButtonHint );
//====== resize window if screen too small
QScreen * screen = QGuiApplication::primaryScreen();
QRect screenGeo = screen->geometry();
if( screenGeo.width() < 1000 || screenGeo.height() < 800) {
setGeometry(0, 0, screenGeo.width() - 100, screenGeo.height() - 100);
}else{
setGeometry(0, 0, 1000, 800);
}
enableSignalSlot = false;
isACQStarted = false;
@ -90,16 +99,6 @@ Scope::Scope(Digitizer ** digi, unsigned int nDigi, ReadDataThread ** readDataTh
xaxis->setLabelFormat("%.0f");
xaxis->setTitleText("Time [ns]");
updateTraceThread = new TimingThread();
updateTraceThread->SetWaitTimeinSec(ScopeUpdateMiliSec / 1000.);
connect(updateTraceThread, &TimingThread::timeUp, this, &Scope::UpdateScope);
updateScalarThread = new TimingThread();
updateScalarThread->SetWaitTimeinSec(2);
connect(updateScalarThread, &TimingThread::timeUp, this, [=](){
emit UpdateScaler();
});
NullThePointers();
//*================================== UI
@ -148,12 +147,39 @@ Scope::Scope(Digitizer ** digi, unsigned int nDigi, ReadDataThread ** readDataTh
if( digi[ID]->GetDPPType() == V1730_DPP_PSD_CODE ) SetUpPanel_PSD();
if( digi[ID]->GetDPPType() == V1740_DPP_QDC_CODE ) SetUpPanel_QDC();
if( digi[ID]->GetDPPType() == V1730_DPP_PHA_CODE ) {
QValueAxis * yaxis = qobject_cast<QValueAxis*> (plot->axes(Qt::Vertical).first());
yaxis->setRange(-(0x1FFF), 0x1FFF);
}
if( digi[ID]->GetDPPType() == V1730_DPP_PSD_CODE ) {
QValueAxis * yaxis = qobject_cast<QValueAxis*> (plot->axes(Qt::Vertical).first());
yaxis->setRange(0, 0x3FFF);
}
if( digi[ID]->GetDPPType() == V1740_DPP_QDC_CODE ) {
QValueAxis * yaxis = qobject_cast<QValueAxis*> (plot->axes(Qt::Vertical).first());
yaxis->setRange(0, 0xFFF);
}
ReadSettingsFromBoard();
if( saveACQStartStatus )StartScope();
});
if( digi[ID]->GetDPPType() == V1730_DPP_PHA_CODE ) {
QValueAxis * yaxis = qobject_cast<QValueAxis*> (plot->axes(Qt::Vertical).first());
yaxis->setRange(-(0x1FFF), 0x1FFF);
}
if( digi[ID]->GetDPPType() == V1730_DPP_PSD_CODE ) {
QValueAxis * yaxis = qobject_cast<QValueAxis*> (plot->axes(Qt::Vertical).first());
yaxis->setRange(0, 0x3FFF);
}
if( digi[ID]->GetDPPType() == V1740_DPP_QDC_CODE ) {
QValueAxis * yaxis = qobject_cast<QValueAxis*> (plot->axes(Qt::Vertical).first());
yaxis->setRange(0, 0xFFF);
}
connect(cbScopeCh, &RComboBox::currentIndexChanged, this, [=](){
if( !enableSignalSlot ) return;
@ -216,7 +242,7 @@ Scope::Scope(Digitizer ** digi, unsigned int nDigi, ReadDataThread ** readDataTh
QLabel * lbhints = new QLabel("Type 'r' to restore view, '+/-' Zoom in/out, arrow key to pan.", this);
layout->addWidget(lbhints, rowID, 0, 1, 4);
QLabel * lbinfo = new QLabel("Trace updates every " + QString::number(updateTraceThread->GetWaitTimeinSec()) + " sec.", this);
QLabel * lbinfo = new QLabel("Trace updates every " + QString::number(ScopeUpdateMiliSec / 1000.) + " sec.", this);
lbinfo->setAlignment(Qt::AlignRight);
layout->addWidget(lbinfo, rowID, 6);
@ -265,35 +291,32 @@ Scope::Scope(Digitizer ** digi, unsigned int nDigi, ReadDataThread ** readDataTh
UpdatePanelFromMomeory();
if( digi[ID]->GetDPPType() == V1730_DPP_PHA_CODE ) {
QValueAxis * yaxis = qobject_cast<QValueAxis*> (plot->axes(Qt::Vertical).first());
yaxis->setRange(-(0x1FFF), 0x1FFF);
}
if( digi[ID]->GetDPPType() == V1730_DPP_PSD_CODE ) {
QValueAxis * yaxis = qobject_cast<QValueAxis*> (plot->axes(Qt::Vertical).first());
yaxis->setRange(0, 0x3FFF);
}
if( digi[ID]->GetDPPType() == V1740_DPP_QDC_CODE ) {
QValueAxis * yaxis = qobject_cast<QValueAxis*> (plot->axes(Qt::Vertical).first());
yaxis->setRange(0, 0xFFF);
}
workerThread = new QThread(this);
scopeWorker = new ScopeWorker(this);
scopeTimer = new QTimer(this);
scopeWorker->moveToThread(workerThread);
// Setup the timer to trigger every second
connect(scopeTimer, &QTimer::timeout, scopeWorker, [=](){
scopeWorker->UpdateScope();
});
workerThread->start();
enableSignalSlot = true;
}
Scope::~Scope(){
DebugPrint("%s", "Scope");
updateTraceThread->Stop();
updateTraceThread->quit();
updateTraceThread->wait();
delete updateTraceThread;
updateScalarThread->Stop();
updateScalarThread->quit();
updateScalarThread->wait();
delete updateScalarThread;
scopeTimer->stop();
// scalarTimer->stop();
if( workerThread->isRunning() ){
workerThread->quit();
workerThread->wait();
}
for( int i = 0; i < MaxNumberOfTrace; i++) delete dataTrace[i];
delete plot;
@ -352,9 +375,9 @@ void Scope::StartScope(){
//save present settings, channleMap, trigger condition
traceOn[ID] = digi[ID]->IsRecordTrace();
digi[ID]->SetBits(DPP::BoardConfiguration, DPP::Bit_BoardConfig::RecordTrace, 1, -1);
chMask = digi[ID]->GetSettingFromMemory(DPP::RegChannelEnableMask);
if( digi[ID]->GetDPPType() == DPPTypeCode::DPP_PHA_CODE ){
chMask = digi[ID]->GetSettingFromMemory(DPP::RegChannelEnableMask);
dppAlg = digi[ID]->GetSettingFromMemory(DPP::DPPAlgorithmControl, ch);
dppAlg2 = digi[ID]->GetSettingFromMemory(DPP::PHA::DPPAlgorithmControl2_G, ch);
@ -363,10 +386,13 @@ void Scope::StartScope(){
digi[ID]->SetBits(DPP::PHA::DPPAlgorithmControl2_G, DPP::PHA::Bit_DPPAlgorithmControl2::LocalShapeTriggerMode, 0, ch);
digi[ID]->SetBits(DPP::PHA::DPPAlgorithmControl2_G, DPP::PHA::Bit_DPPAlgorithmControl2::LocalTrigValidMode, 0, ch);
digi[ID]->WriteRegister(DPP::RegChannelEnableMask, (1 << ch));
}
if( digi[ID]->GetDPPType() == DPPTypeCode::DPP_PSD_CODE ){
chMask = digi[ID]->GetSettingFromMemory(DPP::RegChannelEnableMask);
dppAlg = digi[ID]->GetSettingFromMemory(DPP::DPPAlgorithmControl, ch);
dppAlg2 = digi[ID]->GetSettingFromMemory(DPP::PSD::DPPAlgorithmControl2_G, ch);
@ -375,14 +401,24 @@ void Scope::StartScope(){
digi[ID]->SetBits(DPP::PSD::DPPAlgorithmControl2_G, DPP::PSD::Bit_DPPAlgorithmControl2::LocalShapeTriggerMode, 0, ch);
digi[ID]->SetBits(DPP::PSD::DPPAlgorithmControl2_G, DPP::PSD::Bit_DPPAlgorithmControl2::LocalTrigValidMode, 0, ch);
digi[ID]->WriteRegister(DPP::RegChannelEnableMask, (1 << ch));
}
if( digi[ID]->GetDPPType() == DPPTypeCode::DPP_QDC_CODE ){
chMask = digi[ID]->GetSettingFromMemory(DPP::QDC::GroupEnableMask);
subChMask = digi[ID]->GetSettingFromMemory(DPP::QDC::SubChannelMask);
dppAlg = digi[ID]->GetSettingFromMemory(DPP::QDC::DPPAlgorithmControl, ch);
digi[ID]->SetBits(DPP::QDC::DPPAlgorithmControl, DPP::QDC::Bit_DPPAlgorithmControl::TriggerMode, 0, ch); //set self-triiger
digi[ID]->WriteRegister(DPP::QDC::GroupEnableMask, (1 << (ch/8)));
uint32_t haha = (1 << (ch%8));
if( ch/8 == 0 ) haha |= 0x1; //must include the first subchannel
digi[ID]->WriteRegister(DPP::QDC::SubChannelMask, haha);
}
digi[ID]->WriteRegister(DPP::RegChannelEnableMask, (1 << ch));
//=========== start
digi[ID]->WriteRegister(DPP::SoftwareClear_W, 1);
@ -422,8 +458,7 @@ void Scope::StartScope(){
}
updateTraceThread->start();
updateScalarThread->start();
scopeTimer->start(ScopeUpdateMiliSec);
bnScopeStart->setEnabled(false);
bnScopeStart->setStyleSheet("");
@ -434,7 +469,7 @@ void Scope::StartScope(){
EnableControl(false);
TellACQOnOff(true);
emit TellACQOnOff(true);
isACQStarted = true;
@ -445,13 +480,8 @@ void Scope::StopScope(){
if( !digi ) return;
// printf("------ Scope::%s \n", __func__);
updateTraceThread->Stop();
updateTraceThread->quit();
updateTraceThread->exit();
updateScalarThread->Stop();
updateScalarThread->quit();
updateScalarThread->exit();
scopeTimer->stop();
// scalarTimer->stop();
if( chkSoleRun->isChecked() ){
@ -467,25 +497,27 @@ void Scope::StopScope(){
digiMTX[ID].lock();
digi[ID]->StopACQ();
digi[ID]->ReadACQStatus();
digiMTX[ID].unlock();
//restore setting
digi[ID]->SetBits(DPP::BoardConfiguration, DPP::Bit_BoardConfig::RecordTrace, traceOn[ID], -1);
digi[ID]->WriteRegister(DPP::RegChannelEnableMask, chMask);
if( digi[ID]->GetDPPType() == DPPTypeCode::DPP_PHA_CODE ){
digi[ID]->WriteRegister(DPP::DPPAlgorithmControl, dppAlg, oldCh);
digi[ID]->WriteRegister(DPP::PHA::DPPAlgorithmControl2_G, dppAlg2, oldCh);
digi[ID]->WriteRegister(DPP::RegChannelEnableMask, chMask);
}
if( digi[ID]->GetDPPType() == DPPTypeCode::DPP_PSD_CODE ){
digi[ID]->WriteRegister(DPP::DPPAlgorithmControl, dppAlg, oldCh);
digi[ID]->WriteRegister(DPP::PSD::DPPAlgorithmControl2_G, dppAlg2, oldCh);
digi[ID]->WriteRegister(DPP::RegChannelEnableMask, chMask);
}
if( digi[ID]->GetDPPType() == DPPTypeCode::DPP_QDC_CODE ){
digi[ID]->WriteRegister(DPP::QDC::DPPAlgorithmControl, dppAlg, oldCh);
digi[ID]->WriteRegister(DPP::QDC::GroupEnableMask, chMask);
digi[ID]->WriteRegister(DPP::QDC::SubChannelMask, subChMask);
}
}else{
@ -498,9 +530,9 @@ void Scope::StopScope(){
readDataThread[iDigi]->wait();
readDataThread[iDigi]->SetScopeMode(false);
}
digiMTX[iDigi].lock();
digi[iDigi]->StopACQ();
digi[iDigi]->ReadACQStatus();
//digi[iDigi]->GetData()->PrintAllData();
digiMTX[iDigi].unlock();
@ -511,6 +543,8 @@ void Scope::StopScope(){
}
runStatus->setStyleSheet(""); // cheated, don;t know why digi[iDigi]->GetACQStatusFromMemory(), sometimes return ACQ one.
emit UpdateOtherPanels();
bnScopeStart->setEnabled(true);
@ -523,7 +557,7 @@ void Scope::StopScope(){
EnableControl(true);
TellACQOnOff(false);
emit TellACQOnOff(false);
isACQStarted = false;
@ -736,7 +770,7 @@ void Scope::SetUpSpinBox(RSpinBox * &sb, QString str, int row, int col, const Re
value = uint16_t((1.0 - sb->value()/100.) * 0xFFFF);
}
if( para == DPP::PHA::TriggerThreshold ){
if( para == DPP::PHA::TriggerThreshold || para == DPP::PSD::TriggerThreshold){
value = sb->value();
}
@ -745,7 +779,7 @@ void Scope::SetUpSpinBox(RSpinBox * &sb, QString str, int row, int col, const Re
if( digi[ID]->GetDPPType() == DPPTypeCode::DPP_QDC_CODE ){
int grp = ch/8; // convert ch to grp
digiMTX[ID].lock();
digi[ID]->WriteRegister(para, value, grp);
digi[ID]->WriteRegister(para, value, grp);
digiMTX[ID].unlock();
}else{
digiMTX[ID].lock();
@ -1254,6 +1288,7 @@ void Scope::UpdatePanel_PSD(){
UpdateSpinBox(sbShortGate, DPP::PSD::ShortGateWidth);
UpdateSpinBox(sbLongGate, DPP::PSD::LongGateWidth);
UpdateSpinBox(sbGateOffset, DPP::PSD::GateOffset);
UpdateSpinBox(sbThreshold, DPP::PSD::TriggerThreshold);
uint32_t BdCfg = digi[ID]->GetSettingFromMemory(DPP::BoardConfiguration, ch);

28
Scope.h
View File

@ -12,6 +12,7 @@
#include <QComboBox>
#include <QGridLayout>
#include <QGroupBox>
#include <QTimer>
#include <QLineSeries>
#include <QRubberBand>
#include <QMouseEvent>
@ -22,6 +23,8 @@
#include "CustomThreads.h"
#include "CustomWidgets.h"
class ScopeWorker; //Forward declaration
//^====================================================
//^====================================================
class Scope : public QMainWindow{
@ -51,7 +54,6 @@ signals:
void CloseWindow();
void SendLogMsg(const QString &msg);
void TellACQOnOff(const bool onOff);
void UpdateScaler();
void UpdateOtherPanels();
private:
@ -84,11 +86,10 @@ private:
bool traceOn[MaxNDigitizer];
uint32_t dppAlg, dppAlg2, chMask; //for single channel run
uint32_t subChMask; // for QDC
unsigned short oldCh, oldDigi;
ReadDataThread ** readDataThread;
TimingThread * updateTraceThread;
TimingThread * updateScalarThread;
bool enableSignalSlot;
@ -147,8 +148,29 @@ private:
//sbGateOffset -> GateOffset
//sbTriggerHoldOff ->Trigger Hold Off
QThread * workerThread;
ScopeWorker * scopeWorker;
QTimer * scopeTimer;
};
//^#======================================================== ScopeWorker
class ScopeWorker : public QObject{
Q_OBJECT
public:
ScopeWorker(Scope * parent): SS(parent){}
public slots:
void UpdateScope(){
SS->UpdateScope();
emit workDone();
}
signals:
void workDone();
private:
Scope * SS;
};
#endif

View File

@ -4,21 +4,29 @@
#include <QGroupBox>
#include <QStandardItemModel>
#include <QLabel>
#include <QRandomGenerator>
// #include <QScreen>
SingleSpectra::SingleSpectra(Digitizer ** digi, unsigned int nDigi, QString rawDataPath, QMainWindow * parent) : QMainWindow(parent){
DebugPrint("%s", "SingleSpectra");
this->digi = digi;
this->nDigi = nDigi;
this->rawDataPath = rawDataPath;
this->settingPath = rawDataPath + "/HistogramSettings.txt";
maxFillTimeinMilliSec = 1000;
maxFillTimePerDigi = maxFillTimeinMilliSec/nDigi;
maxFillTimeinMilliSec = SingleHistogramFillingTime;
isSignalSlotActive = true;
setWindowTitle("Single Histograms");
setGeometry(0, 0, 1000, 800);
//setWindowFlags( this->windowFlags() & ~Qt::WindowCloseButtonHint );
//====== resize window if screen too small
QScreen * screen = QGuiApplication::primaryScreen();
QRect screenGeo = screen->geometry();
if( screenGeo.width() < 1000 || screenGeo.height() < 800) {
setGeometry(0, 0, screenGeo.width() - 100, screenGeo.height() - 100);
}else{
setGeometry(0, 0, 1000, 800);
}
QWidget * layoutWidget = new QWidget(this);
setCentralWidget(layoutWidget);
@ -43,15 +51,17 @@ SingleSpectra::SingleSpectra(Digitizer ** digi, unsigned int nDigi, QString rawD
isSignalSlotActive = true;
//printf("oldCh = %d \n", oldCh);
if( oldCh >= digi[index]->GetNumInputCh()) {
cbCh->setCurrentIndex(0);
}else{
if( oldCh >= 0 ){
cbCh->setCurrentIndex(oldCh);
}else{
cbCh->setCurrentIndex(0);
}
}
// if( oldCh >= digi[index]->GetNumInputCh()) {
// cbCh->setCurrentIndex(0);
// }else{
// if( oldCh >= 0 ){
// cbCh->setCurrentIndex(oldCh);
// }else{
// cbCh->setCurrentIndex(0);
// }
// }
cbCh->setCurrentIndex(oldChComboBoxindex[index]);
ChangeHistView();
});
@ -73,101 +83,18 @@ SingleSpectra::SingleSpectra(Digitizer ** digi, unsigned int nDigi, QString rawD
}
});
QPushButton * bnRebinDigi = new QPushButton("Rebin Energy", this);
ctrlLayout->addWidget(bnRebinDigi, 0, 6, 1, 2);
connect(bnRebinDigi, &QPushButton::clicked, this, [=](){
int ID = cbDigi->currentIndex();
int ch = cbCh->currentIndex();
int a_Bin;
float a_Min, a_Max;
if( ch >= 0 ){
a_Bin = hist[ID][ch]->GetNBin();
a_Min = hist[ID][ch]->GetXMin();
a_Max = hist[ID][ch]->GetXMax();
}else{
a_Bin = hist2D[ID]->GetYNBin();
a_Min = hist2D[ID]->GetYMin();
a_Max = hist2D[ID]->GetYMax();
}
//pop up a dialog for nBin and ranhe
QDialog dialog(this);
dialog.setWindowTitle("Rebin histograms");
QFormLayout layout(&dialog);
QLabel * info = new QLabel(&dialog);
info->setStyleSheet("color:red;");
info->setText("This will also clear histogram!!");
layout.addRow(info);
QStringList nameList = {"Num. Bin", "x-Min", "x-Max"};
QLineEdit* lineEdit[3];
for (int i = 0; i < 3; ++i) {
lineEdit[i] = new QLineEdit(&dialog);
layout.addRow(nameList[i] + " : ", lineEdit[i]);
}
lineEdit[0]->setText(QString::number(a_Bin));
lineEdit[1]->setText(QString::number(a_Min));
lineEdit[2]->setText(QString::number(a_Max));
QLabel * msg = new QLabel(&dialog);
msg->setStyleSheet("color:red;");
layout.addRow(msg);
QDialogButtonBox buttonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, &dialog);
layout.addRow(&buttonBox);
double number[3];
QObject::connect(&buttonBox, &QDialogButtonBox::accepted, [&]() {
int OKcount = 0;
bool conversionOk = true;
for( int i = 0; i < 3; i++ ){
number[i] = lineEdit[i]->text().toDouble(&conversionOk);
if( conversionOk ){
OKcount++;
}else{
msg->setText(nameList[i] + " is invalid.");
return;
}
}
if( OKcount == 3 ) {
if( number[2] > number[1] ) {
dialog.accept();
}else{
msg->setText(nameList[2] + " is smaller than " + nameList[1]);
}
}
});
QObject::connect(&buttonBox, &QDialogButtonBox::rejected, [&]() { dialog.reject();});
if( dialog.exec() == QDialog::Accepted ){
if( hist2D[ID] ) {
hist2D[ID]->RebinY((int)number[0], number[1], number[2]);
hist2D[ID]->rescaleAxes();
hist2D[ID]->UpdatePlot();
}
for( int j = 0; j < digi[ID]->GetNumInputCh(); j++){
if( hist[ID][j] ) {
hist[ID][j]->Rebin((int)number[0], number[1], number[2]);
hist[ID][j]->UpdatePlot();
}
}
}
});
QCheckBox * chkIsFillHistogram = new QCheckBox("Fill Histograms", this);
ctrlLayout->addWidget(chkIsFillHistogram, 0, 8);
connect(chkIsFillHistogram, &QCheckBox::stateChanged, this, [=](int state){ fillHistograms = state;});
chkIsFillHistogram = new QCheckBox("Fill Histograms", this);
ctrlLayout->addWidget(chkIsFillHistogram, 0, 6, 1, 2);
chkIsFillHistogram->setChecked(false);
fillHistograms = false;
isFillingHistograms = false;
QLabel * lbSettingPath = new QLabel( settingPath , this);
ctrlLayout->addWidget(lbSettingPath, 1, 0, 1, 6);
QPushButton * bnSaveButton = new QPushButton("Save Hist. Settings", this);
ctrlLayout->addWidget(bnSaveButton, 1, 6, 1, 2);
connect(bnSaveButton, &QPushButton::clicked, this, &SingleSpectra::SaveSetting);
}
@ -193,6 +120,9 @@ SingleSpectra::SingleSpectra(Digitizer ** digi, unsigned int nDigi, QString rawD
for( int j = 0; j < digi[i]->GetNumInputCh(); j++){
if( i < nDigi ) {
hist[i][j] = new Histogram1D("Digi-" + QString::number(digi[i]->GetSerialNumber()) +", Ch-" + QString::number(j), "Raw Energy [ch]", nBin, eMin, eMax);
if( digi[i]->GetDPPType() == DPPTypeCode::DPP_PSD_CODE ){
hist[i][j]->AddDataList("Short Energy", Qt::green);
}
}else{
hist[i][j] = nullptr;
}
@ -206,20 +136,48 @@ SingleSpectra::SingleSpectra(Digitizer ** digi, unsigned int nDigi, QString rawD
histLayout->addWidget(hist2D[0], 0, 0);
hist2DVisibility[0] = true;
oldBd = 0;
oldCh = digi[0]->GetNumInputCh();
}
//set default oldChComboBoxindex
for( unsigned int i = 0; i < nDigi; i++ ) oldChComboBoxindex[i] = 0;
oldBd = 0;
layout->setStretch(0, 1);
layout->setStretch(1, 6);
ClearInternalDataCount();
workerThread = new QThread(this);
histWorker = new HistWorker(this);
timer = new QTimer(this);
histWorker->moveToThread(workerThread);
// this is another way
// timer = new QTimer();
// timer->moveToThread(workerThread);
// connect(this, &SingleSpectra::startWorkerTimer, timer, static_cast<void(QTimer::*)(int)>(&QTimer::start));
// connect(this, &SingleSpectra::stopWorkerTimer, timer, &QTimer::stop);
isFillingHistograms = false;
connect(timer, &QTimer::timeout, histWorker, &HistWorker::FillHistograms);
connect( histWorker, &HistWorker::workDone, this, &SingleSpectra::ReplotHistograms);
workerThread->start();
}
SingleSpectra::~SingleSpectra(){
DebugPrint("%s", "SingleSpectra");
timer->stop();
if( workerThread->isRunning() ){
workerThread->quit();
workerThread->wait();
}
SaveSetting();
for( unsigned int i = 0; i < nDigi; i++ ){
@ -235,7 +193,6 @@ void SingleSpectra::ClearInternalDataCount(){
for( unsigned int i = 0; i < nDigi; i++){
for( int ch = 0; ch < MaxRegChannel ; ch++) {
lastFilledIndex[i][ch] = -1;
loopFilledIndex[i][ch] = 0;
}
}
}
@ -250,13 +207,13 @@ void SingleSpectra::ChangeHistView(){
//printf("bd : %d, ch : %d \n", bd, ch);
// Remove oldCh
if( oldCh >= 0 && oldCh < digi[oldBd]->GetNumInputCh()){
histLayout->removeWidget(hist[oldBd][oldCh]);
hist[oldBd][oldCh]->setParent(nullptr);
histVisibility[oldBd][oldCh] = false;
}
int oldCh = oldChComboBoxindex[oldBd] == 0 ? digi[oldBd]->GetNumInputCh() : oldChComboBoxindex[oldBd] - 1;
if( oldCh == digi[oldBd]->GetNumInputCh() ){
if( oldChComboBoxindex[oldBd] > 0 ){
histLayout->removeWidget(hist[oldBd][oldCh]);
histVisibility[oldBd][oldCh] = false;
hist[oldBd][oldCh]->setParent(nullptr);
}else{
histLayout->removeWidget(hist2D[oldBd]);
hist2D[oldBd]->setParent(nullptr);
hist2DVisibility[oldBd] = false;
@ -266,7 +223,6 @@ void SingleSpectra::ChangeHistView(){
if( ch >=0 && ch < digi[bd]->GetNumInputCh()) {
histLayout->addWidget(hist[bd][ch], 0, 0);
histVisibility[bd][ch] = true;
hist[bd][ch]->UpdatePlot();
}
@ -277,121 +233,174 @@ void SingleSpectra::ChangeHistView(){
}
oldBd = bd;
oldCh = ch;
// for( unsigned int i = 0; i < nDigi; i++ ){
// if( hist2DVisibility[i] ) printf(" hist2D-%d is visible\n", i);
// for( int j = 0; j < digi[i]->GetNumInputCh(); j++){
// if( histVisibility[i][j] ) printf(" hist-%d-%d is visible\n", i, j);
// }
// }
oldChComboBoxindex[bd] = cbCh->currentIndex();
}
void SingleSpectra::FillHistograms(){
// DebugPrint("%s", "SingleSpectra");
if( !fillHistograms ) return;
timespec t0, t1;
// printf("%s | %d %d \n", __func__, chkIsFillHistogram->checkState(), isFillingHistograms);
if( this->isVisible() == false ) return;
if( chkIsFillHistogram->checkState() == Qt::Unchecked ) return;
if( isFillingHistograms) return;
QVector<int> randomDigiList = generateNonRepeatedCombination(nDigi);
isFillingHistograms = true;
// timespec t0, t1;
timespec ta, tb;
// qDebug() << randomDigiList;
printf("####################### SingleSpectra::%s\n", __func__);
// qDebug() << __func__ << "| thread:" << QThread::currentThreadId();
for( int i = 0; i < nDigi; i++){
int ID = randomDigiList[i];
clock_gettime(CLOCK_REALTIME, &ta);
QVector<int> randomChList = generateNonRepeatedCombination(digi[ID]->GetNumInputCh());
std::vector<int> digiChList; // (digi*1000 + ch)
std::vector<long> digiChLastIndex; // loop * dataSize + index;
std::vector<int> digiChAvalibleData;
std::vector<bool> digiChFilled;
std::vector<int> digiChFilledCount;
// qDebug() << randomChList;
digiMTX[ID].lock();
// digi[ID]->GetData()->PrintAllData();
clock_gettime(CLOCK_REALTIME, &t0);
for( int k = 0; k < digi[ID]->GetNumInputCh(); k ++ ){
int ch = randomChList[k];
int lastIndex = digi[ID]->GetData()->GetDataIndex(ch);
// printf("--- ch %2d | last index %d \n", ch, lastIndex);
if( lastIndex < 0 ) continue;
int loopIndex = digi[ID]->GetData()->GetLoopIndex(ch);
int temp1 = lastIndex + loopIndex * digi[ID]->GetData()->GetDataSize();
int temp2 = lastFilledIndex[ID][ch] + loopFilledIndex[ID][ch] * digi[ID]->GetData()->GetDataSize() + 1;
// printf("loopIndx : %d | ID now : %d, ID old : %d \n", loopIndex, temp1, temp2);
for( int ID = 0; ID < nDigi; ID++){
for( int ch = 0; ch < digi[ID]->GetNumInputCh(); ch++){
int temp1 = digi[ID]->GetData()->GetAbsDataIndex(ch);
int temp2 = lastFilledIndex[ID][ch];
if( temp1 <= temp2 ) continue;
digiChList.push_back( ID*1000 + ch ) ;
digiChLastIndex.push_back(temp1);
digiChAvalibleData.push_back(temp1-temp2);
digiChFilled.push_back(false);
digiChFilledCount.push_back(0);
if( temp1 - temp2 > digi[ID]->GetData()->GetDataSize() ) { //DefaultDataSize = 10k
temp2 = temp1 - digi[ID]->GetData()->GetDataSize();
lastFilledIndex[ID][ch] = lastIndex;
lastFilledIndex[ID][ch] = loopIndex - 1;
}
if( temp1 - temp2 > digi[ID]->GetData()->GetDataSize() ) lastFilledIndex[ID][ch] = temp1 - digi[ID]->GetData()->GetDataSize() ;
// printf("ch %d | regulated ID now %d new %d | last fill idx %d\n", ch, temp2, temp1, lastFilledIndex[ID][ch]);
for( int j = 0 ; j <= temp1 - temp2; j ++){
lastFilledIndex[ID][ch] ++;
if( lastFilledIndex[ID][ch] > digi[ID]->GetData()->GetDataSize() ) {
lastFilledIndex[ID][ch] = 0;
loopFilledIndex[ID][ch] ++;
}
}
}
uShort data = digi[ID]->GetData()->GetEnergy(ch, lastFilledIndex[ID][ch]);
int nSize = digiChList.size();
// printf(" ch: %d, last fill idx : %d | %d \n", ch, lastFilledIndex[ID][ch], data);
if( nSize == 0 ) {
isFillingHistograms = false;
return;
}
hist[ID][ch]->Fill( data );
hist2D[ID]->Fill(ch, data);
}
if( histVisibility[ID][ch] ) hist[ID][ch]->UpdatePlot();
// this method, small trigger rate channel will have more chance to fill all data
do{
size_t filledCount = 0;
for( size_t i = 0; i < digiChFilled.size() ; i++ ){
if( digiChFilled[i] ) filledCount ++;
}
if( filledCount == digiChFilled.size() ) break;
clock_gettime(CLOCK_REALTIME, &t1);
if( t1.tv_nsec - t0.tv_nsec + (t1.tv_sec - t0.tv_sec)*1e9 > maxFillTimePerDigi * 1e6 ) break;
int randomValue = QRandomGenerator::global()->bounded(nSize);
if( digiChFilled[randomValue] == true ) continue;
int ID = digiChList[randomValue] / 1000;
int ch = digiChList[randomValue] % 1000;
// printf(" -------------------- %d / %d | %d\n", randomValue, nSize-1, digiCh);
if( digiChLastIndex[randomValue] <= lastFilledIndex[ID][ch] ) {
digiChFilled[randomValue] = true;
// printf("Digi-%2d ch-%2d all filled | %zu\n", ID, ch, digiChList.size());
continue;
}
if( hist2DVisibility[ID] ) hist2D[ID]->UpdatePlot();
digiMTX[ID].unlock();
lastFilledIndex[ID][ch] ++;
digiChFilledCount[randomValue]++;
uShort data = digi[ID]->GetData()->GetEnergy(ch, lastFilledIndex[ID][ch]);
hist[ID][ch]->Fill( data );
if( digi[ID]->GetDPPType() == DPPTypeCode::DPP_PSD_CODE ){
uShort e2 = digi[ID]->GetData()->GetEnergy2(ch, lastFilledIndex[ID][ch]);
hist[ID][ch]->Fill( e2, 1);
}
hist2D[ID]->Fill(ch, data);
// QCoreApplication::processEvents();
clock_gettime(CLOCK_REALTIME, &tb);
}while( isFillingHistograms && (tb.tv_nsec - ta.tv_nsec)/1e6 + (tb.tv_sec - ta.tv_sec)*1e3 < maxFillTimeinMilliSec );
//*--------------- generate fillign report
for( size_t i = 0; i < digiChFilled.size() ; i++){
printf("Digi-%2d ch-%2d | event filled %d / %d\n", digiChList[i] / 1000, digiChList[i] % 1000, digiChFilledCount[i], digiChAvalibleData[i] );
}
clock_gettime(CLOCK_REALTIME, &tb);
printf("total time : %8.3f ms\n", (tb.tv_nsec - ta.tv_nsec)/1e6 + (tb.tv_sec - ta.tv_sec)*1e3 );
isFillingHistograms = false;
}
void SingleSpectra::ReplotHistograms(){
// qDebug() << __func__ << "| thread:" << QThread::currentThreadId();
int ID = cbDigi->currentData().toInt();
int ch = cbCh->currentData().toInt();
if( ch == digi[ID]->GetNumInputCh()) {
if( hist2DVisibility[ID] ) hist2D[ID]->UpdatePlot();
return;
}
if( histVisibility[ID][ch] ) hist[ID][ch]->UpdatePlot();
}
void SingleSpectra::SaveSetting(){
DebugPrint("%s", "SingleSpectra");
QFile file(rawDataPath + "/singleSpectraSetting.txt");
file.open(QIODevice::Text | QIODevice::WriteOnly);
QFile file(settingPath );
for( unsigned int i = 0; i < nDigi; i++){
file.write(("======= " + QString::number(digi[i]->GetSerialNumber()) + "\n").toStdString().c_str());
for( int ch = 0; ch < digi[i]->GetNumInputCh() ; ch++){
QString a = QString::number(ch).rightJustified(2, ' ');
QString b = QString::number(hist[i][ch]->GetNBin()).rightJustified(6, ' ');
QString c = QString::number(hist[i][ch]->GetXMin()).rightJustified(6, ' ');
QString d = QString::number(hist[i][ch]->GetXMax()).rightJustified(6, ' ');
file.write( QString("%1 %2 %3 %4\n").arg(a).arg(b).arg(c).arg(d).toStdString().c_str() );
if (!file.exists()) {
// If the file does not exist, create it
if (!file.open(QIODevice::WriteOnly)) {
qWarning() << "Could not create file" << settingPath;
} else {
qDebug() << "File" << settingPath << "created successfully";
file.close();
}
QString a = QString::number(digi[i]->GetNumInputCh()).rightJustified(2, ' ');
QString b = QString::number(hist2D[i]->GetXNBin()).rightJustified(6, ' ');
QString c = QString::number(hist2D[i]->GetXMin()).rightJustified(6, ' ');
QString d = QString::number(hist2D[i]->GetXMax()).rightJustified(6, ' ');
QString e = QString::number(hist2D[i]->GetYNBin()).rightJustified(6, ' ');
QString f = QString::number(hist2D[i]->GetYMin()).rightJustified(6, ' ');
QString g = QString::number(hist2D[i]->GetYMax()).rightJustified(6, ' ');
file.write( QString("%1 %2 %3 %4 %5 %6 %7\n").arg(a).arg(b).arg(c).arg(d).arg(e).arg(f).arg(g).toStdString().c_str() );
}
file.write("//========== End of file\n");
file.close();
if( file.open(QIODevice::Text | QIODevice::WriteOnly) ){
for( unsigned int i = 0; i < nDigi; i++){
file.write(("======= " + QString::number(digi[i]->GetSerialNumber()) + "\n").toStdString().c_str());
for( int ch = 0; ch < digi[i]->GetNumInputCh() ; ch++){
QString a = QString::number(ch).rightJustified(2, ' ');
QString b = QString::number(hist[i][ch]->GetNBin()).rightJustified(6, ' ');
QString c = QString::number(hist[i][ch]->GetXMin()).rightJustified(6, ' ');
QString d = QString::number(hist[i][ch]->GetXMax()).rightJustified(6, ' ');
file.write( QString("%1 %2 %3 %4\n").arg(a).arg(b).arg(c).arg(d).toStdString().c_str() );
}
QString a = QString::number(digi[i]->GetNumInputCh()).rightJustified(2, ' ');
QString b = QString::number(hist2D[i]->GetXNBin()-2).rightJustified(6, ' ');
QString c = QString::number(hist2D[i]->GetXMin()).rightJustified(6, ' ');
QString d = QString::number(hist2D[i]->GetXMax()).rightJustified(6, ' ');
QString e = QString::number(hist2D[i]->GetYNBin()-2).rightJustified(6, ' ');
QString f = QString::number(hist2D[i]->GetYMin()).rightJustified(6, ' ');
QString g = QString::number(hist2D[i]->GetYMax()).rightJustified(6, ' ');
file.write( QString("%1 %2 %3 %4 %5 %6 %7\n").arg(a).arg(b).arg(c).arg(d).arg(e).arg(f).arg(g).toStdString().c_str() );
}
file.write("##========== End of file\n");
file.close();
printf("Saved Histogram Settings to %s\n", settingPath.toStdString().c_str());
}else{
printf("%s|cannot open HistogramSettings.txt\n", __func__);
}
}
void SingleSpectra::LoadSetting(){
DebugPrint("%s", "SingleSpectra");
QFile file(rawDataPath + "/singleSpectraSetting.txt");
QFile file(settingPath);
if( file.open(QIODevice::Text | QIODevice::ReadOnly) ){
@ -402,7 +411,7 @@ void SingleSpectra::LoadSetting(){
int digiID = -1;
while ( !line.isNull() ){
if( line.contains("//========== ") ) break;
if( line.contains("##========== ") ) break;
if( line.contains("//") ) continue;
if( line.contains("======= ") ){
digiSN = line.mid(7).toInt();
@ -422,21 +431,21 @@ void SingleSpectra::LoadSetting(){
QStringList list = line.split(QRegularExpression("\\s+"));
list.removeAll("");
if( list.count() != 4 ) {
line = in.readLine();
continue;
}
QVector<int> data;
// if( list.count() != 4 ) {
// line = in.readLine();
// continue;
// }
QVector<float> data;
for( int i = 0; i < list.count(); i++){
data.push_back(list[i].toInt());
data.push_back(list[i].toFloat());
}
if( 0 <= data[0] && data[0] < digi[digiID]->GetNumInputCh() ){
hist[digiID][data[0]]->Rebin(data[1], data[2], data[3]);
hist[digiID][int(data[0])]->Rebin(data[1], data[2], data[3]);
}
if( data[0] == digi[digiID]->GetNumInputCh() && data.size() == 7 ){
hist2D[digiID]->Rebin(data[1], data[2], data[3], data[4], data[5], data[6]);
if( int(data[0]) == digi[digiID]->GetNumInputCh() && data.size() == 7 ){
hist2D[digiID]->Rebin(int(data[1]), data[2], data[3], int(data[4]), data[5], data[6]);
}
}
@ -446,6 +455,8 @@ void SingleSpectra::LoadSetting(){
}else{
printf("%s|cannot open HistogramSettings.txt\n", __func__);
}
}

View File

@ -20,6 +20,7 @@
#include "Histogram1D.h"
#include "Histogram2D.h"
class HistWorker; //Forward decalration
//^====================================================
//^====================================================
@ -31,8 +32,8 @@ public:
~SingleSpectra();
void ClearInternalDataCount();
void SetFillHistograms(bool onOff) { fillHistograms = onOff;}
bool IsFillHistograms() const {return fillHistograms;}
// void SetFillHistograms(bool onOff) { fillHistograms = onOff;}
// bool IsFillHistograms() const {return fillHistograms;}
void LoadSetting();
void SaveSetting();
@ -42,20 +43,42 @@ public:
QVector<int> generateNonRepeatedCombination(int size);
void ReplotHistograms();
signals:
// void startWorkerTimer(int interval);
// void stopWorkerTimer();
public slots:
void FillHistograms();
void ChangeHistView();
void startTimer(){
// printf("timer start\n");
timer->start(maxFillTimeinMilliSec);
// emit startWorkerTimer(maxFillTimeinMilliSec);
}
void stopTimer(){
// printf("timer stop\n");
timer->stop();
// emit stopWorkerTimer();
isFillingHistograms = false; // this will also break the FillHistogram do-loop
ClearInternalDataCount();
}
private:
Digitizer ** digi;
unsigned short nDigi;
long lastFilledIndex[MaxNDigitizer][MaxNChannels]; // index * dataSize + index
bool histVisibility[MaxNDigitizer][MaxNChannels];
bool hist2DVisibility[MaxNDigitizer];
bool isFillingHistograms;
Histogram1D * hist[MaxNDigitizer][MaxNChannels];
Histogram2D * hist2D[MaxNDigitizer];
bool histVisibility[MaxNDigitizer][MaxNChannels];
bool hist2DVisibility[MaxNDigitizer];
QCheckBox * chkIsFillHistogram;
RComboBox * cbDivision;
@ -64,19 +87,38 @@ private:
QGroupBox * histBox;
QGridLayout * histLayout;
int oldBd, oldCh;
int oldBd;
int oldChComboBoxindex[MaxNDigitizer]; // the ID of hist for display
int lastFilledIndex[MaxNDigitizer][MaxNChannels];
int loopFilledIndex[MaxNDigitizer][MaxNChannels];
bool fillHistograms;
QString rawDataPath;
QString settingPath;
unsigned short maxFillTimeinMilliSec;
unsigned short maxFillTimePerDigi;
bool isSignalSlotActive;
QThread * workerThread;
HistWorker * histWorker;
QTimer * timer;
};
// //^#======================================================== HistWorker
class HistWorker : public QObject{
Q_OBJECT
public:
HistWorker(SingleSpectra * parent): SS(parent){}
public slots:
void FillHistograms(){
SS->FillHistograms();
emit workDone();
}
signals:
void workDone();
private:
SingleSpectra * SS;
};
#endif

View File

@ -13,7 +13,9 @@ Analyzer::Analyzer(Digitizer ** digi, unsigned int nDigi, QMainWindow * parent )
setGeometry(0, 0, 1000, 800);
influx = nullptr;
dataBaseIP = "";
dataBaseName = "";
dataBaseToken = "";
dataList = new Data*[nDigi];
typeList.clear();
@ -28,9 +30,9 @@ Analyzer::Analyzer(Digitizer ** digi, unsigned int nDigi, QMainWindow * parent )
isBuildBackward = false;
mb = new MultiBuilder(dataList, typeList, snList);
buildTimerThread = new TimingThread(this);
buildTimerThread->SetWaitTimeinSec(1.0); //^Set event build interval
connect( buildTimerThread, &TimingThread::timeUp, this, &Analyzer::UpdateHistograms);
// buildTimerThread = new TimingThread(this);
// buildTimerThread->SetWaitTimeinSec(1.0); //^Set event build interval
// connect( buildTimerThread, &TimingThread::timeUp, this, &Analyzer::UpdateHistograms);
QWidget * layoutWidget = new QWidget(this);
setCentralWidget(layoutWidget);
@ -40,9 +42,43 @@ Analyzer::Analyzer(Digitizer ** digi, unsigned int nDigi, QMainWindow * parent )
// QPushButton * bnSetting = new QPushButton("Settings", this);
// layout->addWidget(bnSetting);
anaThread = new QThread(this);
anaWorker = new AnalyzerWorker(this);
anaTimer = new QTimer();
isWorking = false;
anaWorker->moveToThread(anaThread);
connect(anaTimer, &QTimer::timeout, anaWorker, [=](){
if( isWorking ) return;
isWorking = true;
anaWorker->UpdateHistograms();
isWorking = false;
});
// connect(anaWorker, &AnalyzerWorker::workDone, this, [=](){
// printf(" --------- work Done\n");
// });
connect( anaWorker, &AnalyzerWorker::workDone, this, &Analyzer::ReplotHistograms);
anaThread->start();
}
Analyzer::~Analyzer(){
printf("Analyzer::%s\n", __func__);
anaTimer->stop();
printf(" is anaThread is running %d \n", anaThread->isRunning());
if( anaThread->isRunning() ){
anaThread->quit();
anaThread->wait();
}
printf("------ end of anaThread \n");
delete influx;
delete mb;
delete [] dataList;
@ -60,6 +96,62 @@ double Analyzer::RandomGauss(double mean, double sigma){
}
void Analyzer::SetDatabase(QString IP, QString Name, QString Token){
dataBaseIP = IP;
dataBaseName = Name;
dataBaseToken = Token;
if( influx ) {
delete influx;
influx = nullptr;
}
influx = new InfluxDB(dataBaseIP.toStdString());
if( influx->TestingConnection() ){
printf("InfluxDB URL (%s) is Valid. Version : %s\n", dataBaseIP.toStdString().c_str(), influx->GetVersionString().c_str());
if( influx->GetVersionNo() > 1 && dataBaseToken.isEmpty() ) {
printf("A Token is required for accessing the database.\n");
delete influx;
influx = nullptr;
return;
}
influx->SetToken(dataBaseToken.toStdString());
//==== chck database exist
influx->CheckDatabases();
std::vector<std::string> databaseList = influx->GetDatabaseList();
bool foundDatabase = false;
for( int i = 0; i < (int) databaseList.size(); i++){
if( databaseList[i] == dataBaseName.toStdString() ) foundDatabase = true;
// printf("%d | %s\n", i, databaseList[i].c_str());
}
if( foundDatabase ){
influx->AddDataPoint("test value=1");
influx->WriteData(dataBaseName.toStdString());
influx->ClearDataPointsBuffer();
if( influx->IsWriteOK() ){
printf("test write database OK.\n");
}else{
printf("################# test write database FAIL.\n");
delete influx;
influx = nullptr;
}
}else{
printf(RED "Database name : %s NOT found.\n" RESET, dataBaseName.toStdString().c_str());
delete influx;
influx = nullptr;
}
}else{
printf(RED "InfluxDB URL (%s) is NOT Valid. \n" RESET, dataBaseIP.toStdString().c_str());
delete influx;
influx = nullptr;
}
}
void Analyzer::RedefineEventBuilder(std::vector<int> idList){
delete mb;
delete [] dataList;
@ -76,31 +168,70 @@ void Analyzer::RedefineEventBuilder(std::vector<int> idList){
mb = new MultiBuilder(dataList, typeList, snList);
}
void Analyzer::StartThread(){
mb->ClearEvents();
buildTimerThread->start();
}
void Analyzer::StopThread(){
// printf("%s\n", __func__);
buildTimerThread->Stop();
buildTimerThread->quit();
buildTimerThread->wait();
}
void Analyzer::BuildEvents(bool verbose){
unsigned int nData = mb->GetNumOfDigitizer();
std::vector<int> idList = mb->GetDigiIDList();
for( unsigned int i = 0; i < nData; i++ ) digiMTX[idList[i]].lock();
// qDebug() << __func__ << "| thread:" << QThread::currentThreadId();
// unsigned int nData = mb->GetNumOfDigitizer();
// std::vector<int> idList = mb->GetDigiIDList();
// for( unsigned int i = 0; i < nData; i++ ) digiMTX[idList[i]].lock();
if( isBuildBackward ){
mb->BuildEventsBackWard(maxNumEventBuilt, verbose);
}else{
mb->BuildEvents(0, 0, verbose);
mb->BuildEvents(0, true, verbose);
}
// mb->PrintStat();
// for( unsigned int i = 0; i < nData; i++ ) digiMTX[idList[i]].unlock();
}
void Analyzer::SetDatabaseButton(){
QDialog dialog;
dialog.setWindowTitle("Influx Database");
QGridLayout layout(&dialog);
//------------------------------
QLabel ipLabel("Database IP : ");
layout.addWidget(&ipLabel, 0, 0);
QLineEdit ipLineEdit;
ipLineEdit.setFixedSize(1000, 20);
ipLineEdit.setText(dataBaseIP);
layout.addWidget(&ipLineEdit, 0, 1);
//------------------------------
QLabel nameLabel("Database Name : ");
layout.addWidget(&nameLabel, 1, 0);
QLineEdit nameLineEdit;
nameLineEdit.setFixedSize(1000, 20);
nameLineEdit.setText(dataBaseName);
layout.addWidget(&nameLineEdit, 1, 1);
//------------------------------
QLabel tokenLabel("Database Token : ");
layout.addWidget(&tokenLabel, 2, 0);
QLineEdit tokenLineEdit;
tokenLineEdit.setFixedSize(1000, 20);
tokenLineEdit.setText(dataBaseToken);
layout.addWidget(&tokenLineEdit, 2, 1);
layout.addWidget(new QLabel("Only for version 2+, version 1+ can be skipped."), 3, 0, 1, 2);
// Buttons for OK and Cancel
QDialogButtonBox buttonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
layout.addWidget(&buttonBox);
QObject::connect(&buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
QObject::connect(&buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);
dialog.resize(400, dialog.sizeHint().height()); // Set the width to 400 pixels
// Show the dialog and get the result
if (dialog.exec() == QDialog::Accepted) {
SetDatabase(ipLineEdit.text().trimmed(), nameLineEdit.text().trimmed(),tokenLineEdit.text().trimmed());
}
for( unsigned int i = 0; i < nData; i++ ) digiMTX[idList[i]].unlock();
}
@ -113,4 +244,9 @@ void Analyzer::SetUpCanvas(){
void Analyzer::UpdateHistograms(){
}
void Analyzer::ReplotHistograms(){
}

View File

@ -17,6 +17,7 @@
#include "CustomWidgets.h"
#include "MultiBuilder.h"
#include "ClassInfluxDB.h"
#include "math.h"
/**************************************
@ -28,10 +29,18 @@ This is the mother of all other derivative analysis class.
derivative class should define the SetUpCanvas() and UpdateHistogram();
After creating a new class based on the Analyzer class,
users need to add the class files to the FSUDAQ_Qt6.pro project file,
include the header file in FSUDAQ.cpp,
modify the MainWindow::OpenAnalyzer() method,
and recompile FSUDAQ to incorporate the changes and activate the custom analyzer.
***************************************/
#include "Histogram1D.h"
#include "Histogram2D.h"
class AnalyzerWorker; //Forward decalration
//^==============================================
//^==============================================
class Analyzer : public QMainWindow{
@ -41,32 +50,48 @@ public:
Analyzer(Digitizer ** digi, unsigned int nDigi, QMainWindow * parent = nullptr);
virtual ~Analyzer();
virtual void SetUpCanvas();
MultiBuilder * GetEventBuilder() { return mb;}
void RedefineEventBuilder(std::vector<int> idList);
void SetBackwardBuild(bool TF, int maxNumEvent = 100) { isBuildBackward = TF; maxNumEventBuilt = maxNumEvent;}
void SetDatabase(QString IP, QString Name, QString Token);
double RandomGauss(double mean, double sigma);
void SetDatabaseButton();
double GetUpdateTimeInSec() const {return waitTimeinSec;}
virtual void SetUpCanvas();
virtual void UpdateHistograms(); // where event-building, analysis, and ploting
virtual void ReplotHistograms();
public slots:
void StartThread();
void StopThread();
virtual void UpdateHistograms(); // where event-building, analysis, and ploting
void startTimer(){
// printf("start timer\n");
mb->ForceStop(false);
anaTimer->start(waitTimeinSec*1000);
}
void stopTimer(){
// printf("stop worker\n");
anaTimer->stop();
mb->ForceStop(true);
mb->ClearEvents();
}
private slots:
protected:
QGridLayout * layout;
void BuildEvents(bool verbose = false);
void SetUpdateTimeInSec(double sec = 1.0) {waitTimeinSec = sec; buildTimerThread->SetWaitTimeinSec(waitTimeinSec);}
void SetUpdateTimeInSec(double sec = 1.0) { waitTimeinSec = sec; }
InfluxDB * influx;
std::string dataBaseName;
QString dataBaseIP;
QString dataBaseName;
QString dataBaseToken;
bool isWorking; // a flag to indicate the worker is working
private:
Digitizer ** digi;
unsigned short nDigi;
@ -79,8 +104,32 @@ private:
MultiBuilder * mb;
bool isBuildBackward;
int maxNumEventBuilt;
TimingThread * buildTimerThread;
// TimingThread * buildTimerThread;
QThread * anaThread;
AnalyzerWorker * anaWorker;
QTimer * anaTimer;
};
#endif
//^================================================ AnalyzerWorker
class AnalyzerWorker : public QObject{
Q_OBJECT
public:
AnalyzerWorker(Analyzer * parent): SS(parent){}
public slots:
void UpdateHistograms(){
SS->UpdateHistograms();
emit workDone();
}
signals:
void workDone();
private:
Analyzer * SS;
};
#endif

View File

@ -2,53 +2,44 @@
#define COINCIDENTANLAYZER_H
#include "Analyser.h"
#include "FSUDAQ.h"
//^===========================================
class CoincidentAnalyzer : public Analyzer{
Q_OBJECT
public:
CoincidentAnalyzer(Digitizer ** digi, unsigned int nDigi, QMainWindow * parent = nullptr): Analyzer(digi, nDigi, parent){
CoincidentAnalyzer(Digitizer ** digi, unsigned int nDigi, QString rawDataPath, QMainWindow * parent = nullptr): Analyzer(digi, nDigi, parent){
this->digi = digi;
this->nDigi = nDigi;
this->rawDataPath = rawDataPath;
SetUpdateTimeInSec(1.0);
//RedefineEventBuilder({0}); // only build for the 0-th digitizer, otherwise, it will build event accross all digitizers
SetBackwardBuild(false, 100); // using normal building (acceding in time) or backward building, int the case of backward building, default events to be build is 100.
evtbder = GetEventBuilder();
evtbder->SetTimeWindow(500);
//========== use the influx from the Analyzer
influx = new InfluxDB("https://fsunuc.physics.fsu.edu/influx/");
dataBaseName = "testing";
mb->SetTimeWindow(500);
allowSignalSlot = false;
SetUpCanvas();
LoadHistRange();
}
~CoincidentAnalyzer(){
SaveHistRange();
}
void SetUpCanvas();
public slots:
void UpdateHistograms();
void ReplotHistograms();
private:
Digitizer ** digi;
unsigned int nDigi;
MultiBuilder *evtbder;
bool allowSignalSlot;
QLineEdit * leInfluxIP;
QLineEdit * leDBName;
// declaie histograms
Histogram2D * h2D;
Histogram1D * h1;
@ -73,35 +64,48 @@ private:
RComboBox * aDigi;
RComboBox * aCh;
void SaveHistRange();
void LoadHistRange();
QString rawDataPath;
void SaveSettings();
void LoadSettings();
};
inline void CoincidentAnalyzer::SetUpCanvas(){
setWindowTitle("Online Coincident Analyzer");
setGeometry(0, 0, 1600, 1000);
{//^====== magnet and reaction setting
{//^====== channel settings
QGroupBox * box = new QGroupBox("Configuration", this);
layout->addWidget(box, 0, 0);
QGridLayout * boxLayout = new QGridLayout(box);
boxLayout->setAlignment(Qt::AlignTop | Qt::AlignLeft);
box->setLayout(boxLayout);
int rowID = 0;
{
chkRunAnalyzer = new QCheckBox("Run Analyzer", this);
boxLayout->addWidget(chkRunAnalyzer, 0, 0);
boxLayout->addWidget(chkRunAnalyzer, rowID, 0);
connect(chkRunAnalyzer, &QCheckBox::stateChanged, this, [=](int state){
sbBuildWindow->setEnabled(state != Qt::Checked);
sbUpdateTime->setEnabled(state != Qt::Checked);
chkBackWardBuilding->setEnabled(state != Qt::Checked);
sbBackwardCount->setEnabled(state != Qt::Checked);
});
QLabel * lbUpdateTime = new QLabel("Update Period [s]", this);
lbUpdateTime->setAlignment(Qt::AlignRight | Qt::AlignCenter);
boxLayout->addWidget(lbUpdateTime, 0, 1);
boxLayout->addWidget(lbUpdateTime, rowID, 1);
sbUpdateTime = new RSpinBox(this, 1);
sbUpdateTime->setMinimum(0.1);
sbUpdateTime->setMaximum(5);
sbUpdateTime->setValue(1);
boxLayout->addWidget(sbUpdateTime, 0, 2);
boxLayout->addWidget(sbUpdateTime, rowID, 2);
connect(sbUpdateTime, &RSpinBox::valueChanged, this, [=](){ sbUpdateTime->setStyleSheet("color : blue"); });
@ -110,17 +114,36 @@ inline void CoincidentAnalyzer::SetUpCanvas(){
SetUpdateTimeInSec(sbUpdateTime->value());
});
QLabel * lbBuildWindow = new QLabel("Event Window [ns]", this);
lbBuildWindow->setAlignment(Qt::AlignRight | Qt::AlignCenter);
boxLayout->addWidget(lbBuildWindow, rowID, 3);
sbBuildWindow = new RSpinBox(this, 0);
sbBuildWindow->setMinimum(1);
sbBuildWindow->setMaximum(9999999999);
sbBuildWindow->setValue(1000);
boxLayout->addWidget(sbBuildWindow, rowID, 4);
connect(sbBuildWindow, &RSpinBox::valueChanged, this, [=](){
sbBuildWindow->setStyleSheet("color : blue;");
});
connect(sbBuildWindow, &RSpinBox::returnPressed, this, [=](){
sbBuildWindow->setStyleSheet("");
mb->SetTimeWindow((int)sbBuildWindow->value());
});
rowID ++;
chkBackWardBuilding = new QCheckBox("Use Backward builder", this);
boxLayout->addWidget(chkBackWardBuilding, 1, 0);
boxLayout->addWidget(chkBackWardBuilding, rowID, 0);
QLabel * lbBKWindow = new QLabel("Max No. Backward Event", this);
lbBKWindow->setAlignment(Qt::AlignRight | Qt::AlignCenter);
boxLayout->addWidget(lbBKWindow, 1, 1);
boxLayout->addWidget(lbBKWindow, rowID, 1);
sbBackwardCount = new RSpinBox(this, 0);
sbBackwardCount->setMinimum(1);
sbBackwardCount->setMaximum(9999);
sbBackwardCount->setValue(100);
boxLayout->addWidget(sbBackwardCount, 1, 2);
boxLayout->addWidget(sbBackwardCount, rowID, 2);
chkBackWardBuilding->setChecked(false);
sbBackwardCount->setEnabled(false);
@ -140,61 +163,48 @@ inline void CoincidentAnalyzer::SetUpCanvas(){
SetBackwardBuild(true, sbBackwardCount->value());
});
QLabel * lbBuildWindow = new QLabel("Event Window [tick]", this);
lbBuildWindow->setAlignment(Qt::AlignRight | Qt::AlignCenter);
boxLayout->addWidget(lbBuildWindow, 2, 1);
sbBuildWindow = new RSpinBox(this, 0);
sbBuildWindow->setMinimum(1);
sbBuildWindow->setMaximum(9999999999);
boxLayout->addWidget(sbBuildWindow, 2, 2);
connect(sbBuildWindow, &RSpinBox::valueChanged, this, [=](){
sbBuildWindow->setStyleSheet("color : blue;");
});
connect(sbBuildWindow, &RSpinBox::returnPressed, this, [=](){
sbBuildWindow->setStyleSheet("");
evtbder->SetTimeWindow((int)sbBuildWindow->value());
});
}
{
QFrame *separator = new QFrame(box);
separator->setFrameShape(QFrame::HLine);
separator->setFrameShadow(QFrame::Sunken);
boxLayout->addWidget(separator, 3, 0, 1, 4);
rowID ++;
QFrame *separator0 = new QFrame(box);
separator0->setFrameShape(QFrame::HLine);
separator0->setFrameShadow(QFrame::Sunken);
boxLayout->addWidget(separator0, rowID, 0, 1, 4);
rowID ++;
QLabel * lbXDigi = new QLabel("X-Digi", this);
lbXDigi->setAlignment(Qt::AlignRight | Qt::AlignCenter);
boxLayout->addWidget(lbXDigi, 4, 0);
boxLayout->addWidget(lbXDigi, rowID, 0);
xDigi = new RComboBox(this);
for(unsigned int i = 0; i < nDigi; i ++ ){
xDigi->addItem("Digi-" + QString::number(digi[i]->GetSerialNumber()), i);
}
boxLayout->addWidget(xDigi, 4, 1);
boxLayout->addWidget(xDigi, rowID, 1);
QLabel * lbXCh = new QLabel("X-Ch", this);
lbXCh->setAlignment(Qt::AlignRight | Qt::AlignCenter);
boxLayout->addWidget(lbXCh, 4, 2);
boxLayout->addWidget(lbXCh, rowID, 2);
xCh = new RComboBox(this);
for( int i = 0; i < digi[0]->GetNumInputCh(); i++) xCh->addItem("Ch-" + QString::number(i), i);
boxLayout->addWidget(xCh, 4, 3);
boxLayout->addWidget(xCh, rowID, 3);
rowID ++;
QLabel * lbYDigi = new QLabel("Y-Digi", this);
lbYDigi->setAlignment(Qt::AlignRight | Qt::AlignCenter);
boxLayout->addWidget(lbYDigi, 5, 0);
boxLayout->addWidget(lbYDigi, rowID, 0);
yDigi = new RComboBox(this);
for(unsigned int i = 0; i < nDigi; i ++ ){
yDigi->addItem("Digi-" + QString::number(digi[i]->GetSerialNumber()), i);
}
boxLayout->addWidget(yDigi, 5, 1);
boxLayout->addWidget(yDigi, rowID, 1);
QLabel * lbYCh = new QLabel("Y-Ch", this);
lbYCh->setAlignment(Qt::AlignRight | Qt::AlignCenter);
boxLayout->addWidget(lbYCh, 5, 2);
boxLayout->addWidget(lbYCh, rowID, 2);
yCh = new RComboBox(this);
for( int i = 0; i < digi[0]->GetNumInputCh(); i++) yCh->addItem("Ch-" + QString::number(i), i);
boxLayout->addWidget(yCh, 5, 3);
boxLayout->addWidget(yCh, rowID, 3);
connect(xDigi, &RComboBox::currentIndexChanged, this, [=](){
allowSignalSlot = false;
@ -241,26 +251,28 @@ inline void CoincidentAnalyzer::SetUpCanvas(){
}
{
rowID ++;
QFrame *separator1 = new QFrame(box);
separator1->setFrameShape(QFrame::HLine);
separator1->setFrameShadow(QFrame::Sunken);
boxLayout->addWidget(separator1, 6, 0, 1, 4);
boxLayout->addWidget(separator1, rowID, 0, 1, 4);
rowID ++;
QLabel * lbaDigi = new QLabel("ID-Digi", this);
lbaDigi->setAlignment(Qt::AlignRight | Qt::AlignCenter);
boxLayout->addWidget(lbaDigi, 7, 0);
boxLayout->addWidget(lbaDigi, rowID, 0);
aDigi = new RComboBox(this);
for(unsigned int i = 0; i < nDigi; i ++ ){
aDigi->addItem("Digi-" + QString::number(digi[i]->GetSerialNumber()), digi[i]->GetSerialNumber());
aDigi->addItem("Digi-" + QString::number(digi[i]->GetSerialNumber()), i);
}
boxLayout->addWidget(aDigi, 7, 1);
boxLayout->addWidget(aDigi, rowID, 1);
QLabel * lbaCh = new QLabel("1D-Ch", this);
lbaCh->setAlignment(Qt::AlignRight | Qt::AlignCenter);
boxLayout->addWidget(lbaCh, 7, 2);
boxLayout->addWidget(lbaCh, rowID, 2);
aCh = new RComboBox(this);
for( int i = 0; i < digi[0]->GetNumInputCh(); i++) aCh->addItem("Ch-" + QString::number(i), i);
boxLayout->addWidget(aCh, 7, 3);
boxLayout->addWidget(aCh, rowID, 3);
connect(aDigi, &RComboBox::currentIndexChanged, this, [=](){
allowSignalSlot = false;
@ -290,13 +302,47 @@ inline void CoincidentAnalyzer::SetUpCanvas(){
}
{
QFrame *separator1 = new QFrame(box);
separator1->setFrameShape(QFrame::HLine);
separator1->setFrameShadow(QFrame::Sunken);
boxLayout->addWidget(separator1, 8, 0, 1, 4);
rowID ++;
QFrame *separator2 = new QFrame(box);
separator2->setFrameShape(QFrame::HLine);
separator2->setFrameShadow(QFrame::Sunken);
boxLayout->addWidget(separator2, rowID, 0, 1, 4);
QPushButton * bnClearHist = new QPushButton("Clear All Hist.");
boxLayout->addWidget(bnClearHist, 9, 1);
rowID ++;
QLabel * lbIP = new QLabel("Database IP :", box);
lbIP->setAlignment(Qt::AlignRight | Qt::AlignCenter);
boxLayout->addWidget(lbIP, rowID, 0);
leInfluxIP = new QLineEdit(box);
leInfluxIP->setReadOnly(true);
boxLayout->addWidget(leInfluxIP, rowID, 1, 1, 3);
QPushButton * bnInflux = new QPushButton("Set Influx", box);
boxLayout->addWidget(bnInflux, rowID, 4);
rowID ++;
QLabel * lbDBName = new QLabel("Database name :", box);
lbDBName->setAlignment(Qt::AlignRight | Qt::AlignCenter);
boxLayout->addWidget(lbDBName, rowID, 0);
leDBName = new QLineEdit(box);
leDBName->setReadOnly(true);
boxLayout->addWidget(leDBName, rowID, 1);
connect(bnInflux, &QPushButton::clicked, this, [=](){
SetDatabaseButton();
if( influx ) {
leDBName->setText(dataBaseName);
leInfluxIP->setText(dataBaseIP);
}
});
// rowID ++;
// QFrame *separator3 = new QFrame(box);
// separator3->setFrameShape(QFrame::HLine);
// separator3->setFrameShadow(QFrame::Sunken);
// boxLayout->addWidget(separator3, rowID, 0, 1, 4);
QPushButton * bnClearHist = new QPushButton("Clear All Hist.", this);
boxLayout->addWidget(bnClearHist, rowID, 2);
connect(bnClearHist, &QPushButton::clicked, this, [=](){
h2D->Clear();
@ -305,17 +351,26 @@ inline void CoincidentAnalyzer::SetUpCanvas(){
hMulti->Clear();
});
}
QPushButton * bnSaveSettings = new QPushButton("Save Settings", this);
boxLayout->addWidget(bnSaveSettings, rowID, 3);
connect(bnSaveSettings, &QPushButton::clicked, this, &CoincidentAnalyzer::SaveSettings);
QPushButton * bnLoadSettings = new QPushButton("Load Settings", this);
boxLayout->addWidget(bnLoadSettings, rowID, 4);
connect(bnLoadSettings, &QPushButton::clicked, this, &CoincidentAnalyzer::LoadSettings);
}
}
//============ histograms
hMulti = new Histogram1D("Multiplicity", "", 10, 0, 10, this);
hMulti = new Histogram1D("Multiplicity", "", 16, 0, 16, this);
layout->addWidget(hMulti, 0, 1);
// the "this" make the histogram a child of the SplitPole class. When SplitPole destory, all childs destory as well.
h2D = new Histogram2D("Coincident Plot", "XXX", "YYY", 100, 0, 5000, 100, 0, 5000, this);
h2D = new Histogram2D("Coincident Plot", "XXX", "YYY", 200, 0, 30000, 200, 0, 30000, this, rawDataPath);
//layout is inheriatge from Analyzer
layout->addWidget(h2D, 1, 0, 2, 1);
@ -327,17 +382,16 @@ inline void CoincidentAnalyzer::SetUpCanvas(){
h2D->SetYTitle("Digi-" + QString::number(digi[bd]->GetSerialNumber()) + ", Ch-" + QString::number(ch));
h2D->UpdatePlot();
h1 = new Histogram1D("1D Plot", "XXX", 300, 0, 5000, this);
h1 = new Histogram1D("1D Plot", "XXX", 300, 0, 30000, this);
h1->SetColor(Qt::darkGreen);
h1->AddDataList("Test", Qt::red); // add another histogram in h1, Max Data List is 10
// h1->AddDataList("Test", Qt::red); // add another histogram in h1, Max Data List is 10
bd = aDigi->currentData().toInt();
ch = aCh->currentData().toInt();
h1->SetXTitle("Digi-" + QString::number(digi[bd]->GetSerialNumber()) + ", Ch-" + QString::number(ch));
h1->UpdatePlot();
layout->addWidget(h1, 1, 1);
h1g = new Histogram1D("1D Plot (PID gated)", "XXX", 300, 0, 5000, this);
h1g = new Histogram1D("1D Plot (PID gated)", "XXX", 300, 0, 30000, this);
h1g->SetXTitle("Digi-" + QString::number(digi[bd]->GetSerialNumber()) + ", Ch-" + QString::number(ch));
h1g->UpdatePlot();
layout->addWidget(h1g, 2, 1);
@ -345,17 +399,25 @@ inline void CoincidentAnalyzer::SetUpCanvas(){
layout->setColumnStretch(0, 1);
layout->setColumnStretch(1, 1);
allowSignalSlot = true;
}
inline void CoincidentAnalyzer::UpdateHistograms(){
// printf(">>>>>>>>>>>>> CoincidentAnalyzer::%s | %d %d %d \n", __func__, this->isVisible(), chkRunAnalyzer->isChecked(), isWorking);
if( this->isVisible() == false ) return;
if( chkRunAnalyzer->isChecked() == false ) return;
BuildEvents(); // call the event builder to build events
unsigned long long t0 = getTime_ns();
BuildEvents(false); // call the event builder to build events
// unsigned long long t1 = getTime_ns();
// printf("Event Build time : %llu ns = %.f msec\n", t1 - t0, (t1-t0)/1e6);
//============ Get events, and do analysis
long eventBuilt = evtbder->eventBuilt;
long eventBuilt = mb->eventBuilt;
if( eventBuilt == 0 ) return;
//============ Get the cut list, if any
@ -374,13 +436,17 @@ inline void CoincidentAnalyzer::UpdateHistograms(){
int y_bd = yDigi->currentData().toInt();
int y_ch = yCh->currentData().toInt();
int a_sn = digi[a_bd]->GetSerialNumber();
int x_sn = digi[x_bd]->GetSerialNumber();
int y_sn = digi[y_bd]->GetSerialNumber();
//============ Processing data and fill histograms
long eventIndex = evtbder->eventIndex;
long eventIndex = mb->eventIndex;
long eventStart = eventIndex - eventBuilt + 1;
if(eventStart < 0 ) eventStart += MaxNEvent;
for( long i = eventStart ; i <= eventIndex; i ++ ){
std::vector<Hit> event = evtbder->events[i];
std::vector<Hit> event = mb->events[i];
hMulti->Fill((int) event.size());
if( event.size() == 0 ) return;
@ -389,17 +455,17 @@ inline void CoincidentAnalyzer::UpdateHistograms(){
int xE = -1, yE = -1;
unsigned long long xT = 0;
for( int k = 0; k < (int) event.size(); k++ ){
//event[k].Print();
if( event[k].sn == a_bd && event[k].ch == a_ch) {
// event[k].Print();
if( event[k].sn == a_sn && event[k].ch == a_ch) {
h1->Fill(event[k].energy);
aE = event[k].energy;
}
if( event[k].sn == x_bd && event[k].ch == x_ch) {
if( event[k].sn == x_sn && event[k].ch == x_ch) {
xE = event[k].energy;
xT = event[k].timestamp;
}
if( event[k].sn == y_bd && event[k].ch == y_ch) yE = event[k].energy;
if( event[k].sn == y_sn && event[k].ch == y_ch) yE = event[k].energy;
}
if( xE >= 0 && yE >= 0 ) h2D->Fill(xE, yE);
@ -415,32 +481,191 @@ inline void CoincidentAnalyzer::UpdateHistograms(){
if( p == 0 && aE >= 0 ) h1g->Fill(aE); // only for the 1st gate
}
}
unsigned long long ta = getTime_ns();
if( ta - t0 > sbUpdateTime->value() * 0.9 * GetUpdateTimeInSec() * 1e9 ) break;
}
if( influx ){
QList<QString> cutNameList = h2D->GetCutNameList();
for( int p = 0; p < cutList.count(); p ++){
if( cutList[p].isEmpty() ) continue;
double dT = (tMax[p]-tMin[p]) / 1e9;
double rate = count[p]*1.0/(dT);
printf("%llu %llu, %f %d\n", tMin[p], tMax[p], dT, count[p]);
printf("%10s | %d | %f Hz \n", cutNameList[p].toStdString().c_str(), count[p], rate);
influx->AddDataPoint("Cut,name=" + cutNameList[p].toStdString()+ " value=" + std::to_string(rate));
}
influx->WriteData(dataBaseName.toStdString());
influx->ClearDataPointsBuffer();
}
}
inline void CoincidentAnalyzer::ReplotHistograms(){
h2D->UpdatePlot();
h1->UpdatePlot();
hMulti->UpdatePlot();
h1g->UpdatePlot();
// QList<QString> cutNameList = h2D->GetCutNameList();
// for( int p = 0; p < cutList.count(); p ++){
// if( cutList[p].isEmpty() ) continue;
// double dT = (tMax[p]-tMin[p]) * tick2ns / 1e9; // tick to sec
// double rate = count[p]*1.0/(dT);
//printf("%llu %llu, %f %d\n", tMin[p], tMax[p], dT, count[p]);
//printf("%10s | %d | %f Hz \n", cutNameList[p].toStdString().c_str(), count[p], rate);
// influx->AddDataPoint("Cut,name=" + cutNameList[p].toStdString()+ " value=" + std::to_string(rate));
// influx->WriteData(dataBaseName);
// influx->ClearDataPointsBuffer();
// }
}
inline void CoincidentAnalyzer::SaveHistRange(){
inline void CoincidentAnalyzer::SaveSettings(){
QString filePath = QFileDialog::getSaveFileName(this,
"Save Settings to File",
QDir::toNativeSeparators(rawDataPath + "/CoinAnaSettings.txt" ),
"Text file (*.txt)");
if (!filePath.isEmpty()){
QFile file(filePath);
if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
QTextStream out(&file);
// Define the text to write
QStringList lines;
lines << QString::number(digi[aDigi->currentData().toInt()]->GetSerialNumber());
lines << QString::number(aCh->currentData().toInt());
lines << QString::number(h1->GetNBin());
lines << QString::number(h1->GetXMin());
lines << QString::number(h1->GetXMax());
lines << QString::number(digi[xDigi->currentData().toInt()]->GetSerialNumber());
lines << QString::number(xCh->currentData().toInt());
lines << QString::number(h2D->GetXNBin());
lines << QString::number(h2D->GetXMin());
lines << QString::number(h2D->GetXMax());
lines << QString::number(digi[yDigi->currentData().toInt()]->GetSerialNumber());
lines << QString::number(yCh->currentData().toInt());
lines << QString::number(h2D->GetYNBin());
lines << QString::number(h2D->GetYMin());
lines << QString::number(h2D->GetYMax());
lines << QString::number(sbUpdateTime->value());
lines << QString::number(chkBackWardBuilding->isChecked());
lines << QString::number(sbBackwardCount->value());
lines<< dataBaseIP;
lines<< dataBaseName;
lines<< dataBaseToken;
lines << "#===== End of File";
// Write each line to the file
for (const QString &line : lines) out << line << "\n";
// Close the file
file.close();
qDebug() << "File written successfully to" << filePath;
}else{
qWarning() << "Unable to open file" << filePath;
}
}
}
inline void CoincidentAnalyzer::LoadHistRange(){
inline void CoincidentAnalyzer::LoadSettings(){
QString filePath = QFileDialog::getOpenFileName(this,
"Load Settings to File",
rawDataPath,
"Text file (*.txt)");
int a_sn, a_ch, a_bin;
float a_min, a_max;
int x_sn, x_ch, x_bin;
float x_min, x_max;
int y_sn, y_ch, y_bin;
float y_min, y_max;
float updateTime = 1.0;
int bkCount = 100;
bool isBkEvtBuild = false;
if (!filePath.isEmpty()) {
QFile file(filePath);
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QTextStream in(&file);
short count = 0;
while (!in.atEnd()) {
QString line = in.readLine();
if( count == 0 ) a_sn = line.toInt();
if( count == 1 ) a_ch = line.toInt();
if( count == 2 ) a_bin = line.toInt();
if( count == 3 ) a_min = line.toFloat();
if( count == 4 ) a_max = line.toFloat();
if( count == 5 ) x_sn = line.toFloat();
if( count == 6 ) x_ch = line.toFloat();
if( count == 7 ) x_bin = line.toFloat();
if( count == 8 ) x_min = line.toFloat();
if( count == 9 ) x_max = line.toFloat();
if( count == 10 ) y_sn = line.toFloat();
if( count == 11 ) y_ch = line.toFloat();
if( count == 12 ) y_bin = line.toFloat();
if( count == 13 ) y_min = line.toFloat();
if( count == 14 ) y_max = line.toFloat();
if( count == 15 ) updateTime = line.toFloat();
if( count == 16 ) isBkEvtBuild = line.toInt();
if( count == 17 ) bkCount = line.toInt();
if( count == 18 ) dataBaseIP = line;
if( count == 19 ) dataBaseName = line;
if( count == 20 ) dataBaseToken = line;
count ++;
}
file.close();
qDebug() << "File read successfully from" << filePath;
if( count >= 21 ){
sbUpdateTime->setValue(updateTime);
chkBackWardBuilding->setChecked(isBkEvtBuild);
sbBackwardCount->setValue(bkCount);
int x_index = xDigi->findText("Digi-" + QString::number(x_sn));
int y_index = yDigi->findText("Digi-" + QString::number(y_sn));
int a_index = aDigi->findText("Digi-" + QString::number(a_sn));
if( x_index == -1 ) qWarning() << " Cannot find digitizer " << x_sn;
if( y_index == -1 ) qWarning() << " Cannot find digitizer " << y_sn;
if( a_index == -1 ) qWarning() << " Cannot find digitizer " << a_sn;
xDigi->setCurrentIndex(x_index);
yDigi->setCurrentIndex(y_index);
aDigi->setCurrentIndex(a_index);
xCh->setCurrentIndex(x_ch);
yCh->setCurrentIndex(y_ch);
aCh->setCurrentIndex(a_ch);
h1->Rebin(a_bin, a_min, a_max);
h1g->Rebin(a_bin, a_min, a_max);
h2D->Rebin(x_bin, x_min, x_max, y_bin, y_min, y_max);
SetDatabase(dataBaseIP, dataBaseName, dataBaseToken);
if( influx ){
leDBName->setText(dataBaseName);
leInfluxIP->setText(dataBaseIP);
}
}
}else {
qWarning() << "Unable to open file" << filePath;
}
}
}

311
analyzers/Cross.h Normal file
View File

@ -0,0 +1,311 @@
#ifndef Cross_h
#define Cross_h
/*********************************************
* This is online analyzer for PID, ANL
*
* Created by Khushi @ 2024-09-03
*
* ******************************************/
#include "Analyser.h"
class Cross : public Analyzer{
public:
Cross(Digitizer ** digi, unsigned int nDigi, QMainWindow * parent = nullptr): Analyzer(digi, nDigi, parent){
SetUpdateTimeInSec(1.0);
RedefineEventBuilder({0}); // only builder for the 0-th digitizer.
tick2ns = digi[0]->GetTick2ns();
SetBackwardBuild(false, 100); // using normal building (acceding in time) or backward building, int the case of backward building, default events to be build is 100.
evtbder = GetEventBuilder();
evtbder->SetTimeWindow(500);
SetDatabase("http://localhost:8086/", "testing", "zKhzKk4Yhf1l9QU-yE2GsIZ1RazqUgoW3NlF8LJqq_xDMwatOJwg1sKrjgq36uLEsQf8Fmn4sJALP7Kkilk14A==");
SetUpCanvas(); // see below
};
void SetUpCanvas();
public slots:
void UpdateHistograms();
void ReplotHistograms();
private:
MultiBuilder *evtbder;
//Histogram2D * hPID;
Histogram1D * hdE; // raw dE (ch=1): ch1
Histogram1D * hE; // raw E (ch=4) : ch4
Histogram1D * hdT; // raw dT (ch=7): ch7
Histogram1D * hTotE; // total energy (dE+E): ch1+ch4
Histogram1D * hTWin; // coincidence time window TWin: (t4-t1)*1e9
Histogram2D * hdEE; // dE versus E : ch1 versus ch4
Histogram2D * hdEtotE; // dE versus totE : ch1 versus (ch1+ch4)
Histogram2D * hdEdT; // dE versus TOF: ch1 versus (t7-t1)*1e9
Histogram1D * hMulti; //Multiplicity of an event
int tick2ns;
int chDE, chE;
float energyDE, energyE, ch7;
unsigned long long t1, t4, t7;
QPushButton * bnClearHist;
QLabel * lbInfluxIP;
RComboBox * cbLocation;
QCheckBox * chkDEFourTime;
};
inline void Cross::ReplotHistograms(){
hdE->UpdatePlot();
hE->UpdatePlot();
hdT->UpdatePlot();
hTotE->UpdatePlot();
hdEE->UpdatePlot();
hdEtotE->UpdatePlot();
hdEdT->UpdatePlot();
hTWin->UpdatePlot();
hMulti->UpdatePlot();
}
inline void Cross::SetUpCanvas(){
setGeometry(0, 0, 2000, 1000);
//============ histograms
//hPID = new Histogram2D("RAISOR", "E", "dE", 100, 0, 5000, 100, 0, 5000, this);
//layout->addWidget(hPID, 2, 0);
int row = 0;
cbLocation = new RComboBox(this);
cbLocation->addItem("Cross", 0);
cbLocation->addItem("Target", 1);
layout->addWidget(cbLocation, row, 0);
connect(cbLocation, &RComboBox::currentIndexChanged, this, [=](){
switch (cbLocation->currentData().toInt() ) {
case 0 : {
hdE->SetLineTitle("raw dE (ch = 0)");
hE->SetLineTitle("raw E (ch = 2)");
hdE->replot();
hE->replot();
chDE = 0;
chE = 2;
//Can also set histograms range
}
break;
case 1 : {
hdE->SetLineTitle("raw dE (ch = 1)");
hE->SetLineTitle("raw E (ch = 4)");
hdE->replot();
hE->replot();
chDE = 1;
chE = 4;
//Can also set histograms range
}
}
});
chkDEFourTime = new QCheckBox("dE channel / 4", this);
layout->addWidget(chkDEFourTime, row, 1);
bnClearHist = new QPushButton("Clear All Hist.", this);
layout->addWidget(bnClearHist, row, 2);
connect( bnClearHist, &QPushButton::clicked, this, [=](){
hdE->Clear();
hE->Clear();
hdT->Clear();
hTotE->Clear();
hdEE->Clear();
hdEtotE->Clear();
hdEdT->Clear();
hTWin->Clear();
hMulti->Clear();
});
QString haha;
if( influx ) {
haha = dataBaseIP + ", DB : " + dataBaseName;
}else{
haha = "No influxDB connection.";
}
lbInfluxIP = new QLabel( haha , this);
if( influx == nullptr ) lbInfluxIP->setStyleSheet("color : red;");
layout->addWidget(lbInfluxIP, row, 3, 1, 3);
row ++;
hdEE = new Histogram2D("dE vs E", "E[ch]", "dE[ch]", 500, -100, 5000, 500, -100, 5000, this);
layout->addWidget(hdEE, row, 0, 1, 2);
hdE = new Histogram1D("raw dE (ch=0)", "dE [ch]", 300, 0, 5000, this);
layout->addWidget(hdE, row, 2);
hE = new Histogram1D("raw E (ch=2)", "E [ch]", 300, 0, 10000, this);
layout->addWidget(hE, row, 3);
hTotE = new Histogram1D("total energy (dE+E)", "TotE [ch]", 300, 0, 16000, this);
layout->addWidget(hTotE, row, 4);
hMulti = new Histogram1D("Multiplicity", "", 10, 0, 10, this);
layout->addWidget(hMulti, row, 5);
row ++;
hdEtotE = new Histogram2D("dE vs TotE", "TotE[ch]", "dE[ch]", 500, 0, 10000, 500, 0, 5000, this);
layout->addWidget(hdEtotE, row, 0, 1, 2);
hdT = new Histogram1D("raw dT (ch=7)", "dT [ch]", 300, 0, 1000, this);
layout->addWidget(hdT, row, 2);
hdEdT = new Histogram2D("dE vs TOF", "TOF [ns]", "dE", 100, 0, 500, 100, 0, 4000, this);
layout->addWidget(hdEdT, row, 3);
hTWin = new Histogram1D("coincidence time window", "TWin [ns]", 100, 0, 100, this);
layout->addWidget(hTWin, row, 4);
}
inline void Cross::UpdateHistograms(){
if( this->isVisible() == false ) return;
BuildEvents(false); // call the event builder to build events
//============ Get events, and do analysis
long eventBuilt = evtbder->eventBuilt;
if( eventBuilt == 0 ) return;
//============ Get the cut list, if any
QList<QPolygonF> cutList1 = hdEE->GetCutList();
const int nCut1 = cutList1.count();
unsigned long long tMin1[nCut1], tMax1[nCut1];
unsigned int count1[nCut1];
QList<QPolygonF> cutList2 = hdEtotE->GetCutList();
const int nCut2 = cutList2.count();
unsigned long long tMin2[nCut2], tMax2[nCut2];
unsigned int count2[nCut2];
//============ Processing data and fill histograms
long eventIndex = evtbder->eventIndex;
long eventStart = eventIndex - eventBuilt + 1;
if(eventStart < 0 ) eventStart += MaxNEvent;
for( int i = 0; i < nCut1; i++) {
tMin1[i] = -1;
tMax1[i] = 0;
count1[i] = 0;
}
for( int i = 0; i < nCut2; i++) {
tMin2[i] = -1;
tMax2[i] = 0;
count2[i] = 0;
}
for( long i = eventStart ; i <= eventIndex; i ++ ){
std::vector<Hit> event = evtbder->events[i];
//printf("-------------- %ld\n", i);
if( event.size() == 0 ) return;
hMulti->Fill(event.size());
energyDE = -100; t1 = 0;
energyE = -100; t4 = 0;
ch7 = -100; t7 = 0;
for( int k = 0; k < (int) event.size(); k++ ){
//event[k].Print();
if( event[k].ch == chDE ) {energyDE = event[k].energy; t1 = event[k].timestamp;} // Reads channel 0 of the digitizer corresponding to dE
if( event[k].ch == chE ) {energyE = event[k].energy; t4 = event[k].timestamp;} // Reads channel 2 of the digitizer corresponding to E
if( event[k].ch == 7 ) {ch7 = event[k].energy; t7 = event[k].timestamp;} //RF Timing if setup
}
// printf("(E, dE) = (%f, %f)\n", E, dE);
//hPID->Fill(ch4 , ch1); // x, y
//etotal = ch1*0.25*0.25 + ch4
if( energyDE > 0 ) hdE->Fill(energyDE);
if( energyE > 0 ) hE->Fill(energyE);
if( ch7 > 0 ) hdT->Fill(ch7);
if( energyDE > 0 && energyE > 0 ){
hTotE->Fill(0.25 * energyDE + energyE);
hdEE->Fill(energyE,energyDE);
if( t4 > t1 ) {
hTWin->Fill((t4-t1));
}else{
hTWin->Fill((t1-t4));
}
hdEtotE->Fill( (chkDEFourTime->isChecked() ? 0.25 : 1) * energyDE + energyE,energyDE);
}
if( energyDE > 0 && ch7 > 0) hdEdT->Fill((t7-t1)*1e9,energyDE);
//check events inside any Graphical cut and extract the rate
// if( ch1 == 0 && ch4 == 0 ) continue;
for(int p = 0; p < cutList1.count(); p++ ){
if( cutList1[p].isEmpty() ) continue;
if( cutList1[p].containsPoint(QPointF(energyE, energyDE), Qt::OddEvenFill) ){
if( t1 < tMin1[p] ) tMin1[p] = t1;
if( t1 > tMax1[p] ) tMax1[p] = t1;
count1[p] ++;
//printf("hdEE.... %d \n", count1[p]);
}
}
for(int p = 0; p < cutList2.count(); p++ ){
if( cutList2[p].isEmpty() ) continue;
if( cutList2[p].containsPoint(QPointF(energyDE+energyE,energyDE), Qt::OddEvenFill) ){
if( t1 < tMin2[p] ) tMin2[p] = t1;
if( t1 > tMax2[p] ) tMax2[p] = t1;
count2[p] ++;
//printf("hdEtotE.... %d \n", count2[p]);
}
}
}
for(int p = 0; p < cutList2.count(); p++ ){
printf("hdEE.... %d %d \n", p, count1[p]);
}
//========== output to Influx
QList<QString> cutNameList1 = hdEE->GetCutNameList();
for( int p = 0; p < cutList1.count(); p ++){
if( cutList1[p].isEmpty() ) continue;
double dT = (tMax1[p]-tMin1[p]) / 1e9; // tick to sec
double rate = count1[p]*1.0/(dT);
//printf("%llu %llu, %f %d\n", tMin1[p], tMax1[p], dT, count1[p]);
printf("%10s | %d | %f Hz \n", cutNameList1[p].toStdString().c_str(), count1[p], rate);
if( influx ){
influx->AddDataPoint("Cut,name=" + cutNameList1[p].toStdString()+ " value=" + std::to_string(rate));
influx->WriteData("testing");
influx->ClearDataPointsBuffer();
}
}
}
#endif

View File

@ -5,6 +5,8 @@
#include "Isotope.h"
#include <map>
#include <QApplication>
// #include <QScreen>
namespace EncoreChMap{
@ -82,8 +84,15 @@ private:
inline void Encore::SetUpCanvas(){
setGeometry(0, 0, 1600, 1600);
//====== resize window if screen too small
QScreen * screen = QGuiApplication::primaryScreen();
QRect screenGeo = screen->geometry();
if( screenGeo.width() < 1000 || screenGeo.height() < 1000) {
setGeometry(0, 0, screenGeo.width() - 100, screenGeo.height() -100);
}else{
setGeometry(0, 0, 1000, 1000);
}
// setGeometry(0, 0, 1600, 1600);
chkRunAnalyzer = new QCheckBox("Run Analyzer", this);
layout->addWidget(chkRunAnalyzer, 0, 0);

178
analyzers/MUSICAnalyzer.h Normal file
View File

@ -0,0 +1,178 @@
#ifndef MUSICANLAYZER_H
#define MUSICANLAYZER_H
#include "Analyser.h"
#include "Isotope.h"
#include <map>
#include <QApplication>
// #include <QScreen>
namespace MUSICChMap{
const std::map<unsigned short, int> SN2Bd = {
{16828, 0},
{16829, 1},
{16827, 2},
{23986, 3}
};
//Left 0->15
//Right 16->31
//Individual{32=Grid, 33=S0, 34=cathode, 35=S17, 36=Si_dE, 100>pulser},
//-1=empty
const int mapping[4][16] = {
// 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
{34, -1, 1, -1, 33, 101, 5, -1, 0, -1, 9, -1, 17, 13, -1, 32},
{ 2, -1, 16, -1, 21, 102, 20, -1, 8, -1, 24, -1, 27, 28, -1, 14},
{19, -1, 3, -1, 6, 103, 7, -1, 25, -1, 11, -1, 12, 15, -1, 10},
{ 4, -1, 18, 36, 23, 104, 22, -1, 29, -1, 26, -1, 31, 30, -1, 35}
};
// Gain matching [ch][bd]
const double corr[16][4] = {
{ 1.00000, 1.00000, 1.00000, 1.0000},
{ 1.00000, 1.00000, 1.03158, 1.0000},
{ 1.00000, 1.00000, 0.99240, 1.0000},
{ 1.00000, 1.03704, 0.94004, 1.0000},
{ 1.01031, 1.02084, 1.10114, 1.0000},
{ 1.00000, 0.94685, 1.00513, 1.0000},
{ 1.00000, 1.03431, 1.00513, 1.0000},
{ 1.00000, 0.92670, 0.96078, 1.0000},
{ 1.03431, 0.94685, 0.96314, 1.0000},
{ 1.00000, 1.03158, 0.95145, 1.0000},
{ 0.95145, 1.00256, 0.97270, 1.0000},
{ 1.00000, 1.00256, 0.90950, 1.0000},
{ 1.03704, 0.99492, 0.98740, 1.0000},
{ 1.00000, 1.00000, 0.99746, 1.0000},
{ 0.96078, 1.03980, 1.00513, 1.0000},
{ 1.00000, 1.05095, 1.00000, 1.0000},
};
};
class MUSIC : public Analyzer{
Q_OBJECT
public:
MUSIC(Digitizer ** digi, unsigned int nDigi, QMainWindow * parent = nullptr): Analyzer(digi, nDigi, parent){
SetUpdateTimeInSec(1.0);
SetBackwardBuild(true, 100); // using normal building (acceding in time) or backward building, int the case of backward building, default events to be build is 100.
evtbder = GetEventBuilder();
evtbder->SetTimeWindow(10000);
SetUpCanvas();
}
// MUSIC(){};
void SetUpCanvas();
public slots:
void UpdateHistograms();
private:
MultiBuilder *evtbder;
Histogram2D * hLeft;
Histogram2D * hRight;
Histogram2D * hLR;
Histogram1D * hMulti;
QCheckBox * chkRunAnalyzer;
};
inline void MUSIC::SetUpCanvas(){
//====== resize window if screen too small
QScreen * screen = QGuiApplication::primaryScreen();
QRect screenGeo = screen->geometry();
if( screenGeo.width() < 1000 || screenGeo.height() < 1000) {
setGeometry(0, 0, screenGeo.width() - 100, screenGeo.height() -100);
}else{
setGeometry(0, 0, 1000, 1000);
}
// setGeometry(0, 0, 1600, 1600);
chkRunAnalyzer = new QCheckBox("Run Analyzer", this);
layout->addWidget(chkRunAnalyzer, 0, 0);
hLeft = new Histogram2D("Left", "Ch", "Energy", 16, 0, 16, 200, 0, 200, this);
layout->addWidget(hLeft, 1, 0);
hRight = new Histogram2D("Right", "Ch", "Energy", 16, 0, 16, 200, 0, 200, this);
layout->addWidget(hRight, 1, 1);
hLR = new Histogram2D("Left + Right", "Ch", "Energy", 17, 0, 16, 200, 0, 200, this);
layout->addWidget(hLR, 2, 0);
hMulti = new Histogram1D("Multi", "multiplicity", 40, 0, 40);
layout->addWidget(hMulti, 2, 1);
}
inline void MUSIC::UpdateHistograms(){
if( this->isVisible() == false ) return;
if( chkRunAnalyzer->isChecked() == false ) return;
BuildEvents(false); // call the event builder to build events
//============ Get events, and do analysis
long eventBuilt = evtbder->eventBuilt;
if( eventBuilt == 0 ) return;
//============ Processing data and fill histograms
long eventIndex = evtbder->eventIndex;
long eventStart = eventIndex - eventBuilt + 1;
if(eventStart < 0 ) eventStart += MaxNEvent;
// printf("MUSIC::%s----------- 2 : %ld %ld \n", __func__, eventStart, eventIndex);
for( long i = eventStart ; i <= eventIndex; i ++ ){
std::vector<Hit> event = evtbder->events[i];
// printf("MUSIC::%s----------- %ld, %zu\n", __func__, i, event.size());
hMulti->Fill((int) event.size());
if( event.size() == 0 ) return;
double sum[17] = {0};
for( int k = 0; k < (int) event.size(); k++ ){
// printf("--- %d\n", k);
int bd = MUSICChMap::SN2Bd.at(event[k].sn);
int ch = event[k].ch;
int ID = MUSICChMap::mapping[bd][ch];
if( ID < 0 ) continue;
double eC = event[k].energy;
if( 0 <= ID && ID < 16 ) {
eC *= MUSICChMap::corr[ch][bd];
hLeft->Fill(ID, eC);
sum[ID] += eC;
}
if( 16 <= ID && ID < 32 ) {
eC *= MUSICChMap::corr[ch][bd];
hRight->Fill(ID-16, eC );
sum[ID-16] += eC ;
}
}
for( int ch = 0; ch < 17; ch++){
if( sum[ch] > 0 ) hLR->Fill(ch, sum[ch]);
//printf("%d | sum %d\n", ch, sum[ch]);
}
}
hLeft->UpdatePlot();
hRight->UpdatePlot();
hMulti->UpdatePlot();
hLR->UpdatePlot();
}
#endif

233
analyzers/NeutronGamma.h Normal file
View File

@ -0,0 +1,233 @@
#ifndef NEUTRONGAMMA_H
#define NEUTRONGAMMA_H
/***********************************\
*
* This Analyzer does not use event builder,
* this simply use the energy_short and energy_long for each data.
*
*************************************/
#include <QMainWindow>
#include <QChart>
#include <QChartView>
#include <QLabel>
#include <QPushButton>
#include <QCheckBox>
#include <QLineEdit>
#include <QGridLayout>
#include <QGroupBox>
#include <QVector>
#include <QRandomGenerator>
#include "Analyser.h"
//^====================================================
//^====================================================
class NeutronGamma : public Analyzer{
Q_OBJECT
public:
NeutronGamma(Digitizer ** digi, unsigned int nDigi, QString rawDataPath, QMainWindow * parent = nullptr): Analyzer(digi, nDigi, parent){
this->digi = digi;
this->nDigi = nDigi;
this->settingPath = rawDataPath + "/NG_HistogramSettings.txt";
SetUpdateTimeInSec(1.0);
isSignalSlotActive = false;
SetUpCanvas();
ClearInternalDataCount();
};
~NeutronGamma(){
// for( unsigned int i = 0; i < nDigi; i++ ){
// for( int ch = 0; ch < digi[i]->GetNumInputCh(); ch++){
// delete hist2D[i][ch];
// }
// }
delete hist2D;
}
void ClearInternalDataCount();
// void LoadSetting();
// void SaveSetting();
public slots:
void UpdateHistograms();
void ReplotHistograms();
private:
QVector<int> generateNonRepeatedCombination(int size);
void SetUpCanvas();
Digitizer ** digi;
unsigned short nDigi;
Histogram2D * hist2D;
RComboBox * cbDigi;
RComboBox * cbCh;
QGroupBox * histBox;
QGridLayout * histLayout;
int lastFilledIndex[MaxNDigitizer][MaxNChannels];// absolute data index = loop * dataSize + index
bool fillHistograms;
QString settingPath;
unsigned short maxFillTimeinMilliSec;
unsigned short maxFillTimePerDigi;
bool isSignalSlotActive;
};
inline void NeutronGamma::SetUpCanvas(){
setWindowTitle("Neutron-Gamma Separation");
QScreen * screen = QGuiApplication::primaryScreen();
QRect screenGeo = screen->geometry();
if( screenGeo.width() < 1000 || screenGeo.height() < 800) {
setGeometry(0, 0, screenGeo.width() - 100, screenGeo.height() - 100);
}else{
setGeometry(0, 0, 1000, 800);
}
QWidget * layoutWidget = new QWidget(this);
setCentralWidget(layoutWidget);
QVBoxLayout * layout = new QVBoxLayout(layoutWidget);
layoutWidget->setLayout(layout);
{//^==================================
QGroupBox * controlBox = new QGroupBox("Control", this);
layout->addWidget(controlBox);
QGridLayout * ctrlLayout = new QGridLayout(controlBox);
controlBox->setLayout(ctrlLayout);
cbDigi = new RComboBox(this);
for( unsigned int i = 0; i < nDigi; i++) cbDigi->addItem("Digi-" + QString::number( digi[i]->GetSerialNumber() ), i);
ctrlLayout->addWidget(cbDigi, 0, 0, 1, 2);
connect( cbDigi, &RComboBox::currentIndexChanged, this, [=](int index){
isSignalSlotActive = false;
cbCh->clear();
for( int i = 0; i < digi[index]->GetNumInputCh(); i++) cbCh->addItem("ch-" + QString::number( i ), i);
hist2D->Clear();
isSignalSlotActive = true;
});
cbCh = new RComboBox(this);
for( int i = 0; i < digi[0]->GetNumInputCh(); i++) cbCh->addItem("ch-" + QString::number( i ), i);
ctrlLayout->addWidget(cbCh, 0, 2, 1, 2);
// connect( cbCh, &RComboBox::currentIndexChanged, this, &SingleSpectra::ChangeHistView);
connect( cbCh, &RComboBox::currentIndexChanged, this, [=](){
hist2D->Clear();
});
QCheckBox * chkIsFillHistogram = new QCheckBox("Fill Histograms", this);
ctrlLayout->addWidget(chkIsFillHistogram, 0, 8);
connect(chkIsFillHistogram, &QCheckBox::stateChanged, this, [=](int state){ fillHistograms = state;});
chkIsFillHistogram->setChecked(false);
fillHistograms = false;
QLabel * lbSettingPath = new QLabel( settingPath , this);
ctrlLayout->addWidget(lbSettingPath, 1, 0, 1, 8);
}
{//^====================================
histBox = new QGroupBox("Histgrams", this);
layout->addWidget(histBox, 10);
histLayout = new QGridLayout(histBox);
histBox->setLayout(histLayout);
double eMax = 50000;
double eMin = 0;
double nBin = 1000;
// for( unsigned int i = 0; i < MaxNDigitizer; i++){
// if( i >= nDigi ) continue;
// for( int j = 0; j < digi[i]->GetNumInputCh(); j++){
// if( i < nDigi ) {
// hist2D[i][j] = new Histogram2D("Digi-" + QString::number(digi[i]->GetSerialNumber()), "Long Energy [ch]", "Short Energy [ch]", nBin, eMin, eMax, nBin, eMin, eMax);
// }else{
// hist2D[i][j] = nullptr;
// }
// }
// }
// histLayout->addWidget(hist2D[0][0], 0, 0);
hist2D = new Histogram2D("Neutron-Gamma", "Long Energy [ch]", "PSD = (l-s)/l", nBin, eMin, eMax, nBin, 0, 1);
histLayout->addWidget(hist2D, 0, 0);
}
}
inline void NeutronGamma::ClearInternalDataCount(){
for( unsigned int i = 0; i < nDigi; i++){
for( int ch = 0; ch < MaxRegChannel ; ch++) {
lastFilledIndex[i][ch] = -1;
}
}
}
inline void NeutronGamma::UpdateHistograms(){
if( !fillHistograms ) return;
if( this->isVisible() == false ) return;
// qDebug() << __func__ << "| thread:" << QThread::currentThreadId();
int ID = cbDigi->currentData().toInt();
int ch = cbCh->currentData().toInt();
if( digi[ID]->GetData()->GetDataIndex(ch) < 0 ) return;
int dataAvalible = digi[ID]->GetData()->GetAbsDataIndex(ch) - lastFilledIndex[ID][ch];
if( dataAvalible > digi[ID]->GetData()->GetDataSize() ) { //DefaultDataSize = 10k
lastFilledIndex[ID][ch] = digi[ID]->GetData()->GetAbsDataIndex(ch) - digi[ID]->GetData()->GetDataSize();
}
do{
lastFilledIndex[ID][ch] ++;
uShort data_long = digi[ID]->GetData()->GetEnergy(ch, lastFilledIndex[ID][ch]);
uShort data_short = digi[ID]->GetData()->GetEnergy2(ch, lastFilledIndex[ID][ch]);
// printf(" ch: %d, last fill idx : %d | %d \n", ch, lastFilledIndex[ID][ch], data);
double psd = (data_long - data_short) *1.0 / data_long;
hist2D->Fill(data_long, psd);
}while(lastFilledIndex[ID][ch] <= digi[ID]->GetData()->GetAbsDataIndex(ch));
}
inline void NeutronGamma::ReplotHistograms(){
// qDebug() << __func__ << "| thread:" << QThread::currentThreadId();
hist2D->UpdatePlot();
}
inline QVector<int> NeutronGamma::generateNonRepeatedCombination(int size) {
QVector<int> combination;
for (int i = 0; i < size; ++i) combination.append(i);
for (int i = 0; i < size - 1; ++i) {
int j = QRandomGenerator::global()->bounded(i, size);
combination.swapItemsAt(i, j);
}
return combination;
}
#endif

View File

@ -66,7 +66,7 @@ inline void RAISOR::SetUpCanvas(){
inline void RAISOR::UpdateHistograms(){
if( this->isVisible() == false ) return;
BuildEvents(false); // call the event builder to build events
//============ Get events, and do analysis
@ -124,9 +124,10 @@ inline void RAISOR::UpdateHistograms(){
//printf("%10s | %d | %f Hz \n", cutNameList[p].toStdString().c_str(), count[p], rate);
influx->AddDataPoint("Cut,name=" + cutNameList[p].toStdString()+ " value=" + std::to_string(rate));
influx->WriteData(dataBaseName);
influx->WriteData(dataBaseName.toStdString());
influx->ClearDataPointsBuffer();
}
}

93
analyzers/README.md Normal file
View File

@ -0,0 +1,93 @@
# Introduction
This folder stored all online analyzers. The Analyser.cpp/h is the base class for all analyzer.
The Analyzer.cpp/h has the MultiBuilder (to handle event building) and InfluxDB (to handle pushing data to influxDB database) classes. In Addision, it has a QThread, a AnalyzerWorker, and a QTimer, these three object handle the threading of UpdateHistograms().
The AnalyzerWorker moves to the QThread. QTimer::timeout will trigger AnalyzerWorker::UpdateHistograms().
There is an important bool 'isWorking'. This boolean variable is true when AnalyzerWorker::UpdateHistograms() is running, and it is false when finsihed. This prevent UpdateHistograms() runs twice at the same time.
There are two virual methods
- SetupCanvas()
- UpdateHistograms()
Users must implement these two methods in theie custom analyzer.
# Intruction to make new Analyzer
The CoindientAnalyzer.h is a good example.
1. inheirate the Analyzer class
```cpp
class CustomAnalyzer : public Analyzer{
Q_OBJECT
public:
CustomAnalyzer(Digitizer ** digi, unsigned int nDigi, QMainWindow * parent = nullptr): Analyzer(digi, nDigi, parent){
SetUpdateTimeInSec(1.0); // set histogram update period in sec
mb->SetTimeWindow(500); // set the event time windows
// ... other custom stuffs
}
void SetUpCanvas();
public slots:
void UpdateHistograms();
private:
Histogram2D * h2D;
Histogram1D * h1D;
// some priavte variables
}
```
2. implement the SetUpCanvas() method
```cpp
inline void CustomAnalyzer::SetUpCanvas(){
setWindowTitle("Title");
setGeometry(0, 0, 1600, 1000);
h2D = new Histogram2D("Coincident Plot", "XXX", "YYY", 200, 0, 30000, 200, 0, 30000, this, rawDataPath);
//layout is inheriatge from Analyzer
layout->addWidget(h2D, 0, 0); // row-0, col-0
h1 = new Histogram1D("1D Plot", "XXX", 300, 0, 30000, this);
h1->SetColor(Qt::darkGreen);
layout->addWidget(h1, 0, 1); // row-0, col-1
//other GUI elements
}
```
3. implement the UpdateHistograms() method
```cpp
inline void CustomAnalyzer::UpdateHistograms(){
// don't update histogram when the windows not visible
if( this->isVisible() == false ) return;
BuildEvents(false); // call the event builder to build events, no verbose
//check number of event built
long eventBuilt = mb->eventBuilt;
if( eventBuilt == 0 ) return;
//============ Processing data and fill histograms
long eventIndex = mb->eventIndex;
long eventStart = eventIndex - eventBuilt + 1;
if(eventStart < 0 ) eventStart += MaxNEvent;
for( long i = eventStart ; i <= eventIndex; i ++ ){
std::vector<Hit> event = mb->events[i];
//analysis and fill historgam
}
//Render histograms
h2D->UpdatePlot();
h1D->UpdatePlot();
}
```

View File

@ -30,8 +30,7 @@ public:
RedefineEventBuilder({0}); // only build for the 0-th digitizer, otherwise, it will build event accross all digitizers
tick2ns = digi[0]->GetTick2ns();
SetBackwardBuild(false, 100); // using normal building (acceding in time) or backward building, int the case of backward building, default events to be build is 100.
evtbder = GetEventBuilder();
evtbder->SetTimeWindow(500);
mb->SetTimeWindow(3000);
//========== use the influx from the Analyzer
influx = new InfluxDB("https://fsunuc.physics.fsu.edu/influx/");
@ -41,7 +40,7 @@ public:
leTarget->setText("12C");
leBeam->setText("d");
leRecoil->setText("p");
sbBfield->setValue(0.76);
sbBfield->setValue(0.75);
sbAngle->setValue(20);
sbEnergy->setValue(16);
@ -64,11 +63,10 @@ public:
public slots:
void UpdateHistograms();
void ReplotHistograms();
private:
MultiBuilder *evtbder;
// declaie histograms
Histogram2D * hPID;
@ -87,6 +85,7 @@ private:
RSpinBox * sbEnergy;
RSpinBox * sbAngle;
RSpinBox * sbEventWin;
QCheckBox * chkRunAnalyzer;
QLineEdit * leMassTablePath;
@ -212,9 +211,33 @@ inline void SplitPole::SetUpCanvas(){
FillConstants();
});
chkRunAnalyzer = new QCheckBox("Run Analyzer", this);
boxLayout->addWidget(chkRunAnalyzer, 4, 1);
QLabel * lbEventWindow = new QLabel("Event Window [ns] ", box);
lbEventWindow->setAlignment(Qt::AlignRight | Qt::AlignCenter);
boxLayout->addWidget(lbEventWindow, 4, 0);
sbEventWin = new RSpinBox(this);
sbEventWin->setDecimals(0);
sbEventWin->setSingleStep(100);
sbEventWin->setMaximum(1000000);
boxLayout->addWidget(sbEventWin, 4, 1);
sbEventWin->setValue(3000);
connect(sbEventWin, &RSpinBox::returnPressed, this, [=](){
mb->SetTimeWindow(sbEventWin->value());
});
chkRunAnalyzer = new QCheckBox("Run Analyzer", this);
boxLayout->addWidget(chkRunAnalyzer, 4, 3);
connect(chkRunAnalyzer, &QCheckBox::stateChanged, this, [=](int state){
sbBfield->setEnabled(state != Qt::Checked);
leTarget->setEnabled(state != Qt::Checked);
leBeam->setEnabled(state != Qt::Checked);
leRecoil->setEnabled(state != Qt::Checked);
sbEnergy->setEnabled(state != Qt::Checked);
sbAngle->setEnabled(state != Qt::Checked);
sbEventWin->setEnabled(state != Qt::Checked);
});
QFrame *separator = new QFrame(box);
separator->setFrameShape(QFrame::HLine);
@ -298,20 +321,20 @@ inline void SplitPole::SetUpCanvas(){
}
//============ histograms
hMulti = new Histogram1D("Multiplicity", "", 10, 0, 10, this);
hMulti = new Histogram1D("Multiplicity", "", 16, 0, 16, this);
layout->addWidget(hMulti, 0, 1);
// the "this" make the histogram a child of the SplitPole class. When SplitPole destory, all childs destory as well.
hPID = new Histogram2D("Split Pole PID", "Scin-L", "Anode-Font", 100, 0, 5000, 100, 0, 5000, this);
hPID = new Histogram2D("Split Pole PID", "Scin-L", "Anode-Back", 100, 0, 20000, 100, 0, 40000, this);
//layout is inheriatge from Analyzer
layout->addWidget(hPID, 1, 0, 2, 1);
h1 = new Histogram1D("Spectrum", "x", 300, 30, 70, this);
h1 = new Histogram1D("Spectrum", "x1", 300, -200, 200, this);
h1->SetColor(Qt::darkGreen);
//h1->AddDataList("Test", Qt::red); // add another histogram in h1, Max Data List is 10
layout->addWidget(h1, 1, 1);
h1g = new Histogram1D("Spectrum (PID gated)", "Ex", 300, -2, 10, this);
h1g = new Histogram1D("Spectrum (PID gated)", "x1", 300, -200, 200, this);
layout->addWidget(h1g, 2, 1);
layout->setColumnStretch(0, 1);
@ -327,7 +350,7 @@ inline void SplitPole::UpdateHistograms(){
BuildEvents(); // call the event builder to build events
//============ Get events, and do analysis
long eventBuilt = evtbder->eventBuilt;
long eventBuilt = mb->eventBuilt;
if( eventBuilt == 0 ) return;
//============ Get the cut list, if any
@ -337,12 +360,12 @@ inline void SplitPole::UpdateHistograms(){
unsigned int count[nCut]={0};
//============ Processing data and fill histograms
long eventIndex = evtbder->eventIndex;
long eventIndex = mb->eventIndex;
long eventStart = eventIndex - eventBuilt + 1;
if(eventStart < 0 ) eventStart += MaxNEvent;
for( long i = eventStart ; i <= eventIndex; i ++ ){
std::vector<Hit> event = evtbder->events[i];
std::vector<Hit> event = mb->events[i];
//printf("-------------- %ld\n", i);
hMulti->Fill((int) event.size());
@ -353,28 +376,32 @@ inline void SplitPole::UpdateHistograms(){
for( int k = 0; k < (int) event.size(); k++ ){
//event[k].Print();
if( event[k].ch == SPS::ChMap::ScinR ) {hit.eSR = event[k].energy; hit.tSR = event[k].timestamp;}
if( event[k].ch == SPS::ChMap::ScinL ) {hit.eSL = event[k].energy; hit.tSL = event[k].timestamp;}
if( event[k].ch == SPS::ChMap::dFR ) {hit.eFR = event[k].energy; hit.tFR = event[k].timestamp;}
if( event[k].ch == SPS::ChMap::dFL ) {hit.eFL = event[k].energy; hit.tFL = event[k].timestamp;}
if( event[k].ch == SPS::ChMap::dBR ) {hit.eBL = event[k].energy; hit.tBL = event[k].timestamp;}
if( event[k].ch == SPS::ChMap::dBL ) {hit.eBL = event[k].energy; hit.tBL = event[k].timestamp;}
if( event[k].ch == SPS::ChMap::Cathode ) {hit.eCath = event[k].energy; hit.tCath = event[k].timestamp;}
if( event[k].ch == SPS::ChMap::AnodeF ) {hit.eAF = event[k].energy; hit.tAF = event[k].timestamp;}
if( event[k].ch == SPS::ChMap::AnodeB ) {hit.eAB = event[k].energy; hit.tAB = event[k].timestamp;}
if( event[k].ch == SPS::ChMap::ScinR ) {hit.eSR = event[k].energy; hit.tSR = event[k].timestamp + event[k].fineTime/1000.;}
if( event[k].ch == SPS::ChMap::ScinL ) {hit.eSL = event[k].energy; hit.tSL = event[k].timestamp + event[k].fineTime/1000.;}
if( event[k].ch == SPS::ChMap::dFR ) {hit.eFR = event[k].energy; hit.tFR = event[k].timestamp + event[k].fineTime/1000.;}
if( event[k].ch == SPS::ChMap::dFL ) {hit.eFL = event[k].energy; hit.tFL = event[k].timestamp + event[k].fineTime/1000.;}
if( event[k].ch == SPS::ChMap::dBR ) {hit.eBL = event[k].energy; hit.tBL = event[k].timestamp + event[k].fineTime/1000.;}
if( event[k].ch == SPS::ChMap::dBL ) {hit.eBL = event[k].energy; hit.tBL = event[k].timestamp + event[k].fineTime/1000.;}
if( event[k].ch == SPS::ChMap::Cathode ) {hit.eCath = event[k].energy; hit.tCath = event[k].timestamp + event[k].fineTime/1000.;}
if( event[k].ch == SPS::ChMap::AnodeF ) {hit.eAF = event[k].energy; hit.tAF = event[k].timestamp + event[k].fineTime/1000.;}
if( event[k].ch == SPS::ChMap::AnodeB ) {hit.eAB = event[k].energy; hit.tAB = event[k].timestamp + event[k].fineTime/1000.;}
}
hit.CalData();
double pidX = hit.eSL;
unsigned long long tPidX = hit.tSL;
double pidY = hit.eAF;
double pidY = hit.eAB;
hPID->Fill(pidX, pidY); // x, y
h1->Fill(hit.xAvg);
if( pidX > 0 && pidY > 0 ){
hPID->Fill(pidX, pidY); // x, y
}
if( !std::isnan(hit.x1) ) {
h1->Fill(hit.x1);
}
//h1->Fill(hit.eSR, 1);
//check events inside any Graphical cut and extract the rate, using tSR only
for(int p = 0; p < cutList.count(); p++ ){
if( cutList[p].isEmpty() ) continue;
@ -383,20 +410,18 @@ inline void SplitPole::UpdateHistograms(){
if( tPidX > tMax[p] ) tMax[p] = tPidX;
count[p] ++;
//printf(".... %d \n", count[p]);
if( p == 0 ) {
double xAvg = hit.xAvg * 10;
double xAvgC = xAvg * sbRhoScale->value() + sbRhoOffset->value();
h1g->Fill(hit.Rho2Ex(xAvgC/1000.));
// if( p == 0 ) {
// double xAvg = hit.xAvg * 10;
// double xAvgC = xAvg * sbRhoScale->value() + sbRhoOffset->value();
// h1g->Fill(hit.Rho2Ex(xAvgC/1000.));
// }
if( p == 0 ){
h1g->Fill(hit.x1);
}
}
}
}
hPID->UpdatePlot();
h1->UpdatePlot();
hMulti->UpdatePlot();
h1g->UpdatePlot();
QList<QString> cutNameList = hPID->GetCutNameList();
for( int p = 0; p < cutList.count(); p ++){
if( cutList[p].isEmpty() ) continue;
@ -406,11 +431,17 @@ inline void SplitPole::UpdateHistograms(){
//printf("%10s | %d | %f Hz \n", cutNameList[p].toStdString().c_str(), count[p], rate);
influx->AddDataPoint("Cut,name=" + cutNameList[p].toStdString()+ " value=" + std::to_string(rate));
influx->WriteData(dataBaseName);
influx->WriteData(dataBaseName.toStdString());
influx->ClearDataPointsBuffer();
}
}
inline void SplitPole::ReplotHistograms(){
hPID->UpdatePlot();
h1->UpdatePlot();
hMulti->UpdatePlot();
h1g->UpdatePlot();
}
#endif

View File

@ -39,8 +39,8 @@ namespace SPS{
const short ScinL = 1;
const short dFR = 9;
const short dFL = 8;
const short dBR = 10;
const short dBL = 11;
const short dBR = 11;
const short dBL = 10;
const short Cathode = 7;
const short AnodeF = 13;
const short AnodeB = 15;
@ -64,19 +64,19 @@ public:
ClearData();
}
unsigned int eSR; unsigned long long tSR;
unsigned int eSL; unsigned long long tSL;
unsigned int eFR; unsigned long long tFR;
unsigned int eFL; unsigned long long tFL;
unsigned int eBR; unsigned long long tBR;
unsigned int eBL; unsigned long long tBL;
unsigned int eSR; unsigned long long tSR;
unsigned int eSL; unsigned long long tSL;
unsigned int eFR; unsigned long long tFR;
unsigned int eFL; unsigned long long tFL;
unsigned int eBR; unsigned long long tBR;
unsigned int eBL; unsigned long long tBL;
unsigned int eCath; unsigned long long tCath;
unsigned int eAF; unsigned long long tAF;
unsigned int eAB; unsigned long long tAB;
unsigned int eAF; unsigned long long tAF;
unsigned int eAB; unsigned long long tAB;
float eSAvg;
float x1, x2, theta;
float xAvg;
double xAvg;
double GetQ0() const {return Q0;}
double GetRho0() const {return rho0;}
@ -194,14 +194,22 @@ public:
isConstantCal = false;
}
void CalData(){
void CalData(float scale = 2.){
if( eSR > 0 && eSL > 0 ) eSAvg = (eSR + eSL)/2;
if( eSR > 0 && eSL == 0 ) eSAvg = eSR;
if( eSR == 0 && eSL > 0 ) eSAvg = eSL;
if( tFR > 0 && tFL > 0 ) x1 = (tFL - tFR)/2./2.1;
if( tBR > 0 && tBL > 0 ) x2 = (tBL - tBR)/2./1.98;
if( tFR > 0 && tFL > 0 ) {
if( tFL > tFR) x1 = (tFL - tFR)/scale/2.1;
if( tFL < tFR) x1 = (tFR - tFL)/scale/-2.1;
}
if( tBR > 0 && tBL > 0 ) {
if( tBL > tBR) x2 = (tBL - tBR)/scale/1.98;
if( tBR > tBL) x2 = (tBR - tBL)/scale/-1.98;
}
// printf("x1: %f, x2 : %f \n", x1, x2);
if( !std::isnan(x1) && !std::isnan(x2)) {

15
macro.h
View File

@ -11,12 +11,27 @@
#define MaxRecordLength 0x3fff * 8
#define MaxSaveFileSize 1024 * 1024 * 1024 * 2
#define DefaultDataSize 10000 /// store 10k events per channels
#define ScalarUpdateinMiliSec 1000 // msec
#define SingleHistogramFillingTime 900 // msec
#define MaxDisplayTraceTimeLength 20000 //ns
#define ScopeUpdateMiliSec 200 // msec
#define MaxNumberOfTrace 5 // in an event
#define SETTINGSIZE 2048
#define RESET "\033[0m"
#define RED "\033[31m"
#define GREEN "\033[32m"
#define YELLOW "\033[33m"
#define BLUE "\033[34m"
#define MAGENTA "\033[35m"
#define CYAN "\033[36m"
#define WHITE "\033[37m"
#define DAQLockFile "DAQLock.dat"
#define PIDFile "pid.dat"

View File

@ -3,6 +3,7 @@
#include <QProcess>
#include <QPushButton>
#include <QFile>
#include <QLocale>
#include "FSUDAQ.h"
@ -11,24 +12,28 @@
#include <sys/resource.h>
// class CustomApplication : public QApplication{
// public:
// CustomApplication(int &argc, char **argv) : QApplication(argc, argv) {}
#include <csignal>
#include <cstdlib>
#include <iostream>
// protected:
// bool notify(QObject *receiver, QEvent *event) override{
// qDebug() << event->type() << "Receiver:" << receiver;
// return QApplication::notify(receiver, event);
// }
// };
void abortHandler(int signal) {
std::cerr << "Signal received: " << signal << ", aborting..." << std::endl;
std::abort(); // Calls abort to generate core dump
}
int main(int argc, char *argv[]){
std::signal(SIGSEGV, abortHandler);
setpriority(PRIO_PROCESS, 0, -20);
// CustomApplication a(argc, argv);
QApplication a(argc, argv);
setpriority(PRIO_PROCESS, 0, -20);
// Set Locale
QLocale::setDefault(QLocale::system());
// Set Lock file
bool isLock = false;
int pid = 0;
QFile lockFile(DAQLockFile);
@ -70,7 +75,7 @@ int main(int argc, char *argv[]){
pidFile.write( QString::number(QCoreApplication::applicationPid() ).toStdString().c_str() );
pidFile.close();
MainWindow w;
FSUDAQ w;
w.show();
return a.exec();
}