Compare commits

..

No commits in common. "master" and "canvas" have entirely different histories.

72 changed files with 3594 additions and 65733 deletions

29
.gitignore vendored
View File

@ -1,41 +1,15 @@
*.o
*.fsu
*.root
core.FSUDAQ*
FSUDAQ_Qt6
test
test_indep
programSettings.txt
a4818_list.txt
EventBuilder
EventBuilderNew
EventBuilder2
EventBuilderNoTrace
EventBuilder_sortTime
DataGenerator
DataReaderScript
DataReader
pid.dat
DAQLock.dat
DumpFSU2ROOT
SettingsExplorer
AggSeparator
FSU2CAEN
Bin2Root
data
Data
raw_binary
log
*.d
*.pcm
*.txt
*.tar
*.tar.gz
*.BIN
*~
*.autosave
@ -70,5 +44,4 @@ Thumbs.db
*.res
*.rc
/.qmake.cache
/.qmake.stash
*.gdb_history
/.qmake.stash

View File

@ -13,32 +13,6 @@
"cppStandard": "gnu++17",
"intelliSenseMode": "linux-gcc-x64"
},
{
"name": "RyanUbuntu",
"includePath": [
"${workspaceFolder}/**",
"/usr/include/x86_64-linux-gnu/qt6/**",
"/opt/root/include/**"
],
"defines": [],
"compilerPath": "/usr/bin/gcc",
"cStandard": "c17",
"cppStandard": "gnu++17",
"intelliSenseMode": "linux-gcc-x64"
},
{
"name": "Anasen",
"includePath": [
"${workspaceFolder}/**",
"/usr/include/x86_64-linux-gnu/qt6/**",
"/opt/root/include/**"
],
"defines": [],
"compilerPath": "/usr/bin/gcc",
"cStandard": "c17",
"cppStandard": "gnu++17",
"intelliSenseMode": "linux-gcc-x64"
},
{
"name": "Splitpole",
"includePath": [

48
.vscode/settings.json vendored
View File

@ -82,36 +82,39 @@
}
],
"files.associations": {
"*.C": "cpp",
"*.pro": "makefile",
"regex": "cpp",
"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",
"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",
@ -126,35 +129,28 @@
"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"
"variant": "cpp",
"qmainwindow": "cpp",
"qchartview": "cpp"
}
}

View File

@ -1,107 +0,0 @@
/*************
This can be loaded to root and run the DataReader()
***********/
#include "../ClassData.h"
#include "../MultiBuilder.h"
void DataReader(std::string fileName, int DPPType){
Data * data = new Data(64);
data->DPPType = DPPType;
FILE * haha = fopen(fileName.c_str(), "r");
fseek(haha, 0L, SEEK_END);
const long inFileSize = ftell(haha);
printf("%s | file size : %ld Byte = %.2f MB\n", fileName.c_str() , inFileSize, inFileSize/1024./1024.);
fseek(haha, 0, SEEK_SET);
MultiBuilder * mb = new MultiBuilder(data, DPPType, 0);
mb->SetTimeWindow(0);
char * buffer = nullptr;
int countBdAgg = 0;
do{
//long fPos1 = ftell(haha);
unsigned int word[1]; /// 4 bytes
size_t dummy = fread(word, 4, 1, haha);
if( dummy != 1) {
printf("fread error, should read 4 bytes, but read %ld x 4 byte, file pos: %ld byte\n", dummy, ftell(haha));
break;
}
fseek(haha, -4, SEEK_CUR);
short header = ((word[0] >> 28 ) & 0xF);
if( header != 0xA ) break;
unsigned int aggSize = (word[0] & 0x0FFFFFFF) * 4; ///byte
buffer = new char[aggSize];
dummy = fread(buffer, aggSize, 1, haha);
if( dummy != 1) {
printf("fread error, should read %d bytes, but read %ld x %d byte, file pos: %ld byte \n", aggSize, dummy, aggSize, ftell(haha));
break;
}
//long fPos2 = ftell(haha);
countBdAgg ++;
// printf("Board Agg. has %d word = %d bytes | %ld - %ld\n", aggSize/4, aggSize, fPos1, fPos2);
// printf("==================== %d Agg\n", countBdAgg);
data->DecodeBuffer(buffer, aggSize, false, 0); // data own the buffer
data->ClearBuffer(); // this will clear the buffer.
//if( countBdAgg % 100 == 0) data->PrintStat();
//data->ClearData();
//if( countBdAgg > 10 ){
//data->PrintAllData();
//mb->BuildEvents(false, true, false);
//mb->BuildEventsBackWard(false);
//}
}while(!feof(haha) && ftell(haha) < inFileSize);
fclose(haha);
printf("============================ done | Total Agg. %d\n", countBdAgg);
data->PrintStat();
//data->PrintAllData();
mb->BuildEvents(true, true, false);
mb->PrintStat();
delete mb;
delete data;
}
int main(int argc, char **argv){
printf("=========================================\n");
printf("=== *.fsu data reader ===\n");
printf("=========================================\n");
if (argc <= 1) {
printf("Incorrect number of arguments:\n");
printf("%s [inFile] [DPPType] \n", argv[0]);
printf(" +-- PHA = %d\n", DPPTypeCode::DPP_PHA_CODE);
printf(" +-- PSD = %d\n", DPPTypeCode::DPP_PSD_CODE);
printf(" +-- QDC = %d\n", DPPTypeCode::DPP_QDC_CODE);
return 1;
}
DataReader(argv[1], atoi(argv[2]));
return 0;
}

View File

@ -1,191 +0,0 @@
/*************
This can be loaded to root and run the DataReader()
***********/
#include "../ClassData.h"
#include "../MultiBuilder.h"
#include "TROOT.h"
#include "TFile.h"
#include "TTree.h"
int main(int argc, char **argv){
printf("=========================================\n");
printf("=== *.fsu to root ===\n");
printf("=========================================\n");
if (argc <= 3) {
printf("Incorrect number of arguments:\n");
printf("%s [list of inFile\n", argv[0]);
return 1;
}
///============= read input
int nFile = argc - 1;
TString inFileName[nFile];
for( int i = 0 ; i < nFile ; i++){
inFileName[i] = argv[i+1];
}
/// Form outFileName;
TString outFileName = inFileName[0];
int pos = outFileName.Last('/');
outFileName.Remove(0,pos+1);
pos = outFileName.Index("_");
pos = outFileName.Index("_", pos+1);
outFileName.Remove(pos);
outFileName += "_single.root";
printf("-------> Out file name : %s \n", outFileName.Data());
printf(" Number of Files : %d \n", nFile);
printf("===================================== input files:\n");
///============= sorting file by the serial number & order
int ID[nFile]; /// serial+ order*1000;
int type[nFile];
int sn[nFile];
unsigned int fileSize[nFile];
for( int i = 0; i < nFile; i++){
int pos = inFileName[i].Last('/');
int snPos = inFileName[i].Index("_", pos); // first "_"
//snPos = inFileName[i].Index("_", snPos + 1);
sn[i] = atoi(&inFileName[i][snPos+5]);
TString typeStr = &inFileName[i][snPos+9];
typeStr.Resize(3);
if( typeStr == "PHA" ) type[i] = DPPTypeCode::DPP_PHA_CODE;
if( typeStr == "PSD" ) type[i] = DPPTypeCode::DPP_PSD_CODE;
if( typeStr == "QDC" ) type[i] = DPPTypeCode::DPP_QDC_CODE;
int order = atoi(&inFileName[i][snPos+13]);
ID[i] = sn[i] + order * 1000;
FILE * temp = fopen(inFileName[i].Data(), "rb");
if( temp == NULL ) {
fileSize[i] = 0;
}else{
fseek(temp, 0, SEEK_END);
fileSize[i] = ftell(temp);
}
fclose(temp);
}
for( int i = 0; i < nFile; i++) printf("%2d | %s %d %d %u\n", i, inFileName[i].Data(), ID[i], type[i], fileSize[i]);
//*======================================= open raw files
printf("##############################################\n");
FILE ** inFile = new FILE *[nFile];
Data ** data = new Data *[nFile];
for( int i = 0; i < nFile; i++){
inFile[i] = fopen(inFileName[i].Data(), "r");
if( inFile[i] ){
if( type[i] == DPPTypeCode::DPP_PHA_CODE || type[i] == DPPTypeCode::DPP_PSD_CODE ) data[i] = new Data(16);
if( type[i] == DPPTypeCode::DPP_QDC_CODE ) data[i] = new Data(64);
data[i]->DPPType = type[i];
data[i]->boardSN = ID[i]%1000;
}else{
data[i] = nullptr;
}
}
char * buffer = nullptr;
unsigned int word[1]; /// 4 bytes
//============ tree
TFile * rootFile = new TFile(outFileName, "recreate");
TTree * tree = new TTree("tree", outFileName);
unsigned short bd;
unsigned short ch;
unsigned short e;
unsigned long long e_t;
tree->Branch("bd", &bd, "bd/s");
tree->Branch("ch", &ch, "ch/s");
tree->Branch("e", &e, "e/s");
tree->Branch("e_t", &e_t, "e_t/l");
//============
for( int i = 0; i < nFile; i++){
if( inFile[i] == nullptr ) continue;
MultiBuilder * mb = new MultiBuilder(data[i], type[i], sn[i]);
mb->SetTimeWindow(0);
int countBdAgg = 0;
do{
//long fPos1 = ftell(inFile[i]);
size_t dummy = fread(word, 4, 1, inFile[i]);
if( dummy != 1) {
printf("fread error, should read 4 bytes, but read %ld x 4 byte, file pos: %ld byte\n", dummy, ftell(inFile[i]));
break;
}
fseek(inFile[i], -4, SEEK_CUR);
short header = ((word[0] >> 28 ) & 0xF);
if( header != 0xA ) break;
unsigned int aggSize = (word[0] & 0x0FFFFFFF) * 4; ///byte
buffer = new char[aggSize];
dummy = fread(buffer, aggSize, 1, inFile[i]);
if( dummy != 1) {
printf("fread error, should read %d bytes, but read %ld x %d byte, file pos: %ld byte \n", aggSize, dummy, aggSize, ftell(inFile[i]));
break;
}
//long fPos2 = ftell(inFile[i]);
countBdAgg ++;
// printf("Board Agg. has %d word = %d bytes | %ld - %ld\n", aggSize/4, aggSize, fPos1, fPos2);
// printf("==================== %d Agg\n", countBdAgg);
data[i]->DecodeBuffer(buffer, aggSize, false, 0); // data own the buffer
data[i]->ClearBuffer(); // this will clear the buffer.
//============ save data into tree
mb->BuildEvents(true);
for(int k = 0; k < mb->eventBuilt; k++){
bd = ID[i]%1000;
ch = mb->events[k][0].ch;
e = mb->events[k][0].energy;
e_t = mb->events[k][0].timestamp;
tree->Fill();
}
mb->ClearEvents();
data[i]->ClearData();
}while(!feof(inFile[i]) && ftell(inFile[i]) < fileSize[i]);
fclose(inFile[i]);
printf("================ %s done | Total Agg. %d\n", inFileName[i].Data(), countBdAgg);
//data[i]->PrintStat();
//data->PrintAllData();
//mb->BuildEvents(true, true, false);
//mb->PrintStat();
delete mb;
}
tree->Write();
tree->Print();
rootFile->Close();
return 0;
}

View File

@ -1,379 +0,0 @@
#include "fsuReader.h"
#include "TROOT.h"
#include "TSystem.h"
#include "TClonesArray.h"
#include "TGraph.h"
#include "TFile.h"
#include "TTree.h"
#include "TMacro.h"
#include "TMath.h"
#define MAX_TRACE_LENGTH 2000
#define MAX_MULTI 100
struct FileInfo{
std::string fileName;
int fileID;
unsigned long hitCount;
};
#define NMINARG 4
#define debug 0
//^#############################################################
//^#############################################################
int main(int argc, char **argv) {
printf("=========================================\n");
printf("=== *.fsu Events Builder ===\n");
printf("=========================================\n");
if (argc < NMINARG) {
printf("Incorrect number of arguments:\n");
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(" Output file name is contructed from inFile1 \n");
printf("\n");
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;
}
uInt runStartTime = getTime_us();
///============= read input
long timeWindow = atoi(argv[1]);
bool traceOn = atoi(argv[2]);
// 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 + NMINARG -1];}
/// Form outFileName;
TString outFileName = inFileName[0];
int pos = outFileName.Last('/');
pos = outFileName.Index("_", pos+1); // find next "_"
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 += "_" + ( 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(" 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
std::vector<FileInfo> fileList;
unsigned long long int totalHitCount = 0;
FSUReader * readerA = new FSUReader(inFileName[0].Data(), 1, 1);
readerA->ScanNumBlock(0,0);
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->GetTotalHitCount();
for( int i = 1; i < nFile; i++){
FSUReader * readerB = new FSUReader(inFileName[i].Data(), 1, 1);
readerB->ScanNumBlock(0,0);
// 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);
}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);
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() );
}
}
TFile * outRootFile = nullptr;
TTree * tree = nullptr;
unsigned long long evID = 0;
unsigned int multi = 0;
unsigned short sn[MAX_MULTI] = {0}; /// board SN
unsigned short ch[MAX_MULTI] = {0}; /// chID
unsigned short e[MAX_MULTI] = {0}; /// 15 bit
unsigned short e2[MAX_MULTI] = {0}; /// 15 bit
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");
tree->Branch("sn", sn, "sn[multi]/s");
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_t[multi]/l");
tree->Branch("e_f", e_f, "e_f[multi]/s");
tree->Branch("traceLength", traceLength, "traceLength[multi]/s");
if( traceOn ) {
tree->Branch("trace", trace,"trace[multi][MAX_TRACE_LENGTH]/S");
tree->GetBranch("trace")->SetCompressionSettings(205);
}
//*======================================= Open files
printf("========================================= Open files & reading 1st batch.\n");
const short nGroup = fileGroupList.size();
std::vector<Hit> hitList[nGroup];
FSUReader ** reader = new FSUReader * [nGroup];
ulong ID[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, 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 ) {
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;
//find earliest time group;
unsigned long long t0 = -1;
short g0 = 0 ;
for( short i = 0; i < nGroup; i++){
if( hitList[i].size() == 0 ) continue;
if( hitList[i][0].timestamp < t0 ) {
t0 = hitList[i][0].timestamp;
g0 = i;
}
}
tStart = t0;
if( debug ) printf("First timestamp is %llu, group : %u\n", t0, g0);
int nFileFinished = 0;
multi = 0;
evID = 0;
std::vector<Hit> events;
unsigned long long hitProcessed = 0;
printf("========================================= Start Building Events....\n");
do{
//*============= Build events from hitList[i]
if( debug ) printf("################################ ev build %llu \n", evID);
events.clear();
for( short i = 0; i < nGroup; i++){
short ig = (i + g0 ) % nGroup;
if( hitList[ig].size() == 0 ) continue;
//chekc if reached the end of hitList
if( ID[ig] >= hitList[ig].size() ) {
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;
}
if( timeWindow >= 0 ){
do{
if( (long int)(hitList[ig][ID[ig]].timestamp - t0) <= timeWindow ){
events.push_back(hitList[ig][ID[ig]]);
ID[ig] ++;
}else{
break;
}
//check if reached the end of hitList
if( ID[ig] >= hitList[ig].size() ) {
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;
}
}while(ID[ig] < hitList[ig].size());
}else{
events.push_back(hitList[ig].at(ID[ig]));
ID[ig] ++;
}
if( timeWindow < 0) break;
}
if( events.size() > 1 ){
std::sort(events.begin(), events.end(), [](const Hit& a, const Hit& b) {
return a.timestamp < b.timestamp;
});
}
tEnd = events.back().timestamp;
hitProcessed += events.size();
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("\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();}
sn[p] = events[p].sn;
ch[p] = events[p].ch;
e[p] = events[p].energy;
e2[p] = events[p].energy2;
e_t[p] = events[p].timestamp;
e_f[p] = events[p].fineTime;
traceLength[p] = events[p].traceLength;
if( traceOn ){
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];
}
}
}
outRootFile->cd();
tree->Fill();
// tree->Write();
multi = 0;
evID ++;
///===================== find the next first timestamp
t0 = -1;
g0 = -1;
for( int i = 0; i < nGroup; i++) {
if( hitList[i].size() == 0 ) continue;
if( hitList[i][ID[i]].timestamp < t0 ) {
t0 = hitList[i][ID[i]].timestamp;
g0 = i;
}
}
if( debug ) printf("Next First timestamp is %llu, group : %u\n", t0, g0);
//*=============
nFileFinished = 0;
for( int i = 0 ; i < nGroup; i++) {
if( hitList[i].size() == 0 ) {
nFileFinished ++;
continue;
}else{
if( ID[i] >= hitList[i].size( )) {
hitList[i] = reader[i]->ReadBatch(batchSize, traceOn, debug);
ID[i] = 0;
if( hitList[i].size() == 0 ) nFileFinished ++;
}
}
}
if( debug > 1 ) printf("========== nFileFinished : %d\n", nFileFinished);
}while( nFileFinished < nGroup);
tree->Write();
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 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", 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;
}

View File

@ -1,305 +0,0 @@
#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

@ -1,64 +0,0 @@
########################################################################
#
#
#########################################################################
CC = g++
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 ClassDigitizerAPI.o
ALL = test EventBuilder DataReader DumpFSU2ROOT SettingsExplorer FSU2CAEN haha
#########################################################################
all : $(ALL)
clean :
/bin/rm -f $(OBJS) $(ALL)
MultiBuilder.o : ../MultiBuilder.cpp ../MultiBuilder.h ../Hit.h
$(CC) $(COPTS) -c ../MultiBuilder.cpp
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 ClassDigitizerAPI.o
@echo "--------- making test"
$(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"
# $(CC) $(COPTS) -o test_indep test_indep.cpp $(CAENLIBS)
DataReader : DataReaderScript.cpp ../ClassData.h MultiBuilder.o
@echo "--------- making DataReader"
$(CC) $(COPTS) -o DataReader DataReaderScript.cpp ../ClassData.h MultiBuilder.o
EventBuilder : EventBuilder.cpp ../ClassData.h fsuReader.h ../Hit.h
@echo "--------- making EventBuilder"
$(CC) $(COPTS) -o EventBuilder EventBuilder.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"
$(CC) $(COPTS) -o DumpFSU2ROOT DumpFSU2ROOT.cpp ../ClassData.h MultiBuilder.o $(ROOTLIBS)
SettingsExplorer : SettingsExplorer.cpp ../ClassDigitizer.o ../RegisterAddress.h
@echo "--------- making SettingsExplorer"
$(CC) $(COPTS) -o SettingsExplorer SettingsExplorer.cpp ../ClassDigitizer.o $(CAENLIBS)

View File

@ -1,129 +0,0 @@
# About this directory
This stores auxillary programs, mainly focus on reading the *.fsu file, For example, the fsuReader.h is a *.fsu reader.
# Need to Make
```sh
make
```
# fsuReader.h
This declare the FSUReader class. it can be included as a header in a custom cpp file, or it can be loaded on cern root CLI (command line interface).
```sh
>.L fsuReader.h
>FSUReader * reader = new FSUReader(<fileName>, <dataBufferSize>, verbose)
>reader->ScanNumBlock(verbose)
>reader->ReadNextBlock()
```
The FSUReader can also read a fileList as a chain.
Within the FSUReader, there exists a Data Class (defined in ClassData.h). This necessitates the specification of the data buffer size for the reader. The data buffer operates as a circular buffer, typically ranging from 10 to 600, which should be sufficient.
The ScanNumBlock() method not only scans the number of blocks (or aggregations) but also tallies the number of hits.
The FSUReader includes a std::vector<Hit>, which is utilized in the ReadNextBlock(bool traceON = false, int verbose = 0, uShort saveData = 0) function. When saveData = 0, no data is stored in the Hit vector; saveData = 1 excludes trace data, while saveData = 2 includes it. It's worth noting that the Hit vector can be quite memory-intensive, particularly when trace data is included.
The pivotal method for the event builder is the ReadBatch(unsigned int batchSize, bool verbose) function. This method reads a large number of Hits (with a size of batchSize). It effectively reads twice the specified batchSize: the first batch is stored as hitList_A, and the second as hitList_B. By comparing the timestamps of hitList_A and hitList_B, sorting if necessary, the method ensures that both hitLists are time-sorted. It then outputs hitList_A and internally stores hitList_B. Subsequent calls to this method replace hitList_A with hitList_B, retrieve a new batch to serve as the new hitList_B, repeat the sorting process, and output hitList_A.
Occasionally, the earliest timestamp of hitList_B precedes that of hitList_A. In such cases, increasing the batchSize resolves the issue, albeit at the cost of higher memory usage. Typically, a batchSize of 1 million should suffice.
With this approach, it is guaranteed that the output hitList_A is always time-sorted (given the batchSize is big enough), thereby simplifying the event building process.
# EvenBuilder.cpp
This defines the EventBuilder. The arguments are
```sh
./EventBuilder [timeWindow] [withTrace] [inFile1] [inFile2] ....
timeWindow : in ns, -1 = no event building
withTrace : 0 for no trace, 1 for trace
Output file name is contructed from inFile1
```
as an example,
```sh
/EventBuilder 0 0'\ls -1 test_001*.fsu'
```
setting the timeWindow to be -1, will split out a timesorted Hit.
## Important output message
Sometimes, you may encounter following output in red color
```sh
!!!!!!!!!!!!!!!!! ReadBatch | Need to increase the batch size.
```
That means the fsuReder need larger batchSize.
```sh
event 786 has size = 2350 > MAX_MULTI = 2000
```
This indicate the event 786 has event size 2350, which is larger than MAX_MULTI of 2000. depends on your experimental setup. If you think multiplicity more than 2000 makes sense, you can edit the MAX_MULTI in the EventBuilder.cpp.
## output
Evenbuilder output is standard information, an example structure is
```sh
******************************************************************************
*Tree :tree : test_001_379_-1.root *
*Entries : 2017231 : Total = 121385718 bytes File Size = 47528456 *
* : : Tree compression factor = 2.55 *
******************************************************************************
*Br 0 :evID : event_ID/l *
*Entries : 2017231 : Total Size= 16167926 bytes File Size = 4222686 *
*Baskets : 327 : Basket Size= 3835392 bytes Compression= 3.83 *
*............................................................................*
*Br 1 :multi : multi/i *
*Entries : 2017231 : Total Size= 8084409 bytes File Size = 56959 *
*Baskets : 165 : Basket Size= 1917952 bytes Compression= 141.87 *
*............................................................................*
*Br 2 :sn : sn[multi]/s *
*Entries : 2017231 : Total Size= 12143148 bytes File Size = 4648638 *
*Baskets : 406 : Basket Size= 25600000 bytes Compression= 2.61 *
*............................................................................*
*Br 3 :ch : ch[multi]/s *
*Entries : 2017231 : Total Size= 12143148 bytes File Size = 4719909 *
*Baskets : 406 : Basket Size= 25600000 bytes Compression= 2.57 *
*............................................................................*
*Br 4 :e : e[multi]/s *
*Entries : 2017231 : Total Size= 12142738 bytes File Size = 7040714 *
*Baskets : 406 : Basket Size= 25600000 bytes Compression= 1.72 *
*............................................................................*
*Br 5 :e2 : e2[multi]/s *
*Entries : 2017231 : Total Size= 12143148 bytes File Size = 4649857 *
*Baskets : 406 : Basket Size= 25600000 bytes Compression= 2.61 *
*............................................................................*
*Br 6 :e_t : e_timestamp[multi]/l *
*Entries : 2017231 : Total Size= 24270794 bytes File Size = 12883867 *
*Baskets : 649 : Basket Size= 25600000 bytes Compression= 1.88 *
*............................................................................*
*Br 7 :e_f : e_fineTime[multi]/s *
*Entries : 2017231 : Total Size= 12143579 bytes File Size = 4636856 *
*Baskets : 406 : Basket Size= 25600000 bytes Compression= 2.62 *
*............................................................................*
*Br 8 :traceLength : traceLength[multi]/s *
*Entries : 2017231 : Total Size= 12146944 bytes File Size = 4640404 *
*Baskets : 407 : Basket Size= 25600000 bytes Compression= 2.62 *
*............................................................................*
```
# 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
This defines the Setting explorer, the explorer takes the setting *bin file as argument.

View File

@ -1,346 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <iostream>
#include <thread>
#include <fstream>
#include <string>
#include <vector>
#include <stdlib.h>
#include <vector>
#include <bitset>
#include <unistd.h>
#include <limits.h>
#include <ctime>
#include <sys/time.h> /* struct timeval, select() */
#include <termios.h> /* tcgetattr(), tcsetattr() */
#include "../RegisterAddress.h"
#include "../ClassDigitizer.h"
static struct termios g_old_kbd_mode;
static void cooked(void); ///set keyboard behaviour as wait-for-enter
static void uncooked(void); ///set keyboard behaviour as immediate repsond
static void raw(void);
int getch(void);
bool isNumeric(const std::string& str) ;
int keyboardhit();
Digitizer * digi = nullptr;
std::vector<Reg> RegList;
bool QuitFlag = false;
void PrintCommands(){
if (QuitFlag) return;
printf("\n");
printf("\e[96m============= Command List ===================\e[0m\n");
printf("q ) Quit \n");
printf("b ) Print Board Settings\n");
printf("c ) Print Channel Settings\n");
printf("x ) Export binary to text file\n");
printf("* invalid input = back to upper level \n");
}
void keyPressCommand(){
char c = getch();
if (c == 'q') { //========== quit
QuitFlag = true;
}
if (c == 'b') { //==========
if( digi->GetDPPType() == DPPTypeCode::DPP_PHA_CODE || digi->GetDPPType() == DPPTypeCode::DPP_PSD_CODE ){
RegList = RegisterBoardList_PHAPSD;
}else if(digi->GetDPPType() == DPPTypeCode::DPP_QDC_CODE) {
RegList = RegisterBoardList_QDC;
}
for( int i = 0; i < (int) RegList.size(); i++){
std::string typeStr ;
if( RegList[i].GetRWType() == RW::ReadWrite ) typeStr = "R/W";
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 = %10u\n", i,
RegList[i].GetAddress(),
RegList[i].GetNameChar(),
typeStr.c_str(),
value,
value);
}
std::string input = "-1";
cooked();
do{
std::cout << "Enter Setting ID to change the setting : ";
std::getline(std::cin, input);
if( !isNumeric(input) ) break;
int ID = atoi(input.c_str());
if( 0 <= ID && ID < (int) RegList.size() ){
printf("\e[34mSelected %s = 0x%08X = %u \e[0m\n", RegList[ID].GetNameChar(),
digi->GetSettingFromMemory(RegList[ID], 0),
digi->GetSettingFromMemory(RegList[ID], 0));
if( RegList[ID].GetRWType() == RW::ReadONLY ) {
printf("This register is READ-ONLY.\n");
}else if (RegList[ID].GetRWType() == RW::WriteONLY){
printf("This register is WRITE-ONLY, which is a command. no need to set value.\n");
}else{
std::cout << "What value ? ";
std::getline(std::cin, input);
if( isNumeric(input) ){
digi->SetSettingToMemory(RegList[ID], atoi(input.c_str()), 0);
digi->SaveSettingToFile(RegList[ID], atoi(input.c_str()), 0);
printf("\e[31mNow %s = 0x%08X = %u \e[0m\n", RegList[ID].GetNameChar(),
digi->GetSettingFromMemory(RegList[ID], 0),
digi->GetSettingFromMemory(RegList[ID], 0));
}else{
printf("Entered non numerical.\n");
input = "-1";
}
}
}
}while( isNumeric( input) );
uncooked();
}
if( c == 'c' ){
cooked();
std::string input = "-1";
std::cout << "Enter channel number (# of ch = " << digi->GetNumRegChannels() << ") : ";
std::getline(std::cin, input);
if( !isNumeric(input) ) {
uncooked();
return;
};
int ch = atoi(input.c_str());
if( ch < 0 || ch >= digi->GetNumRegChannels() ){
printf("Input channel number = %d, outrange of the supported channel\n", ch);
uncooked();
return;
}
if( digi->GetDPPType() == DPPTypeCode::DPP_PHA_CODE ) RegList = RegisterChannelList_PHA;
if( digi->GetDPPType() == DPPTypeCode::DPP_PSD_CODE ) RegList = RegisterChannelList_PSD;
if( digi->GetDPPType() == DPPTypeCode::DPP_QDC_CODE ) RegList = RegisterChannelList_QDC;
for( int i = 0; i < (int) RegList.size(); i++){
std::string typeStr ;
if( RegList[i].GetRWType() == RW::ReadWrite ) typeStr = "R/W";
if( RegList[i].GetRWType() == RW::ReadONLY ) typeStr = "R ";
if( RegList[i].GetRWType() == RW::WriteONLY ) typeStr = " W";
RegList[i].ActualAddress(ch);
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(),
value,
value,
value * abs(RegList[i].GetPartialStep()));
}
do{
std::cout << "Enter Setting ID to change the setting : ";
std::getline(std::cin, input);
if( !isNumeric(input) ) break;
int ID = atoi(input.c_str());
if( 0 <= ID && ID < (int) RegList.size() ){
printf("\e[34mID=%d | ch-%d | Selected %s = 0x%08X = %u \e[0m\n", ID, ch, RegList[ID].GetNameChar(),
digi->GetSettingFromMemory(RegList[ID], ch),
digi->GetSettingFromMemory(RegList[ID], ch));
if( RegList[ID].GetRWType() == RW::ReadONLY ) {
printf("This register is READ-ONLY.\n");
}else if (RegList[ID].GetRWType() == RW::WriteONLY){
printf("This register is WRITE-ONLY, which is a command. no need to set value.\n");
}else{
std::cout << "What value (negative will change all channels) ? ";
std::getline(std::cin, input);
if( isNumeric(input) ){
int value = atoi(input.c_str());
printf(" input : %s %d\n", input.c_str(), value);
if( value < 0 ){
value = abs(value);
for( int i = 0; i < digi->GetNumRegChannels(); i++){
digi->SetSettingToMemory(RegList[ID], value, i);
digi->SaveSettingToFile(RegList[ID], value, i);
printf("\e[31mNow ch-%2d %s = 0x%08X = %u \e[0m\n", i, RegList[ID].GetNameChar(),
digi->GetSettingFromMemory(RegList[ID], i),
digi->GetSettingFromMemory(RegList[ID], i));
}
}else{
digi->SetSettingToMemory(RegList[ID], value, ch);
digi->SaveSettingToFile(RegList[ID], value, ch);
printf("\e[31mNow ch-%2d %s = 0x%08X = %u \e[0m\n", ch, RegList[ID].GetNameChar(),
digi->GetSettingFromMemory(RegList[ID], ch),
digi->GetSettingFromMemory(RegList[ID], ch));
if( RegList[ID].IsCoupled() ){
int cpCh = (ch%2 == 0 ? ch + 1 : ch - 1);
digi->SetSettingToMemory(RegList[ID], value, cpCh);
digi->SaveSettingToFile(RegList[ID], value, cpCh);
printf("\e[31mNow ch-%2d %s = 0x%08X = %u \e[0m\n", cpCh, RegList[ID].GetNameChar(),
digi->GetSettingFromMemory(RegList[ID], cpCh),
digi->GetSettingFromMemory(RegList[ID], cpCh));
}
}
}else{
printf("Entered non numerical.\n");
input = "-1";
}
}
}
}while( isNumeric( input) );
uncooked();
}
if (c == 'x') { //==========
cooked(); ///set keyboard need enter to responds
std::string input = "haha.txt";
std::cout << "Eneter file name : ";
std::getline(std::cin, input);
digi->SaveAllSettingsAsText(input);
uncooked();
}
}
//################################################
int main(int argc, char **argv) {
printf("=========================================\n");
printf("=== Setting Binary Explorer ===\n");
printf("=========================================\n");
if (argc != 2) {
printf("Incorrect number of arguments:\n");
printf("%s *bin \n", argv[0]);
return 1;
}
digi = new Digitizer();
digi->LoadSettingBinaryToMemory(argv[1]);
if( !(digi->GetDPPType() == DPPTypeCode::DPP_PHA_CODE ||
digi->GetDPPType() == DPPTypeCode::DPP_PSD_CODE ||
digi->GetDPPType() == DPPTypeCode::DPP_QDC_CODE )){
printf("DPP-type not supported. Or Binary file is not supported.\n");
delete digi;
return -1;
}
//digi->PrintSettingFromMemory();
PrintCommands();
do{
if(keyboardhit()) {
keyPressCommand();
PrintCommands();
}
}while(!QuitFlag);
delete digi;
return 0;
}
//################################################
bool isNumeric(const std::string& str) {
try {
size_t pos = 0;
std::stoi(str, &pos);
return pos == str.size(); // Check if the entire string was used in conversion
} catch (...) {
return false;
}
}
static void cooked(void){
tcsetattr(0, TCSANOW, &g_old_kbd_mode);
}
static void uncooked(void){
struct termios new_kbd_mode;
/* put keyboard (stdin, actually) in raw, unbuffered mode */
tcgetattr(0, &g_old_kbd_mode);
memcpy(&new_kbd_mode, &g_old_kbd_mode, sizeof(struct termios));
new_kbd_mode.c_lflag &= ~(ICANON | ECHO);
new_kbd_mode.c_cc[VTIME] = 0;
new_kbd_mode.c_cc[VMIN] = 1;
tcsetattr(0, TCSANOW, &new_kbd_mode);
}
static void raw(void){
static char init;
if(init) return;
/* put keyboard (stdin, actually) in raw, unbuffered mode */
uncooked();
/* when we exit, go back to normal, "cooked" mode */
atexit(cooked);
init = 1;
}
int getch(void){
unsigned char temp;
raw();
/* stdin = fd 0 */
if(read(0, &temp, 1) != 1) return 0;
//printf("%s", &temp);
return temp;
}
int keyboardhit(){
struct timeval timeout;
fd_set read_handles;
int status;
raw();
/* check stdin (fd 0) for activity */
FD_ZERO(&read_handles);
FD_SET(0, &read_handles);
timeout.tv_sec = timeout.tv_usec = 0;
status = select(0 + 1, &read_handles, NULL, NULL, &timeout);
if(status < 0){
printf("select() failed in keyboardhit()\n");
exit(1);
}
return (status);
}

View File

@ -1,274 +0,0 @@
#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

View File

@ -1,194 +0,0 @@
#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

@ -1,633 +0,0 @@
#include "../ClassData.h"
#include "../Hit.h"
#include <algorithm>
#include <filesystem>
#define DEFAULT_HALFBUFFERSIZE 5000000
class FSUReader{
public:
FSUReader();
FSUReader(std::string fileName, uInt dataSize = 100, int verbose = 1);
FSUReader(std::vector<std::string> fileList, uInt dataSize = 100, int verbose = 1);
~FSUReader();
void OpenFile(std::string fileName, uInt dataSize, int verbose = 1);
bool IsOpen() const{return inFile == nullptr ? false : true;}
bool IsEndOfFile() const {
// printf("%s : %d | %ld |%ld\n", __func__, feof(inFile), ftell(inFile), inFileSize);
if(fileList.empty() ) {
if( (uLong )ftell(inFile) >= inFileSize){
return true;
}else{
return false;
}
}else{
if( fileID + 1 == (int) fileList.size() && ((uLong)ftell(inFile) >= inFileSize) ) {
return true;
}else{
return false;
}
}
}
void ScanNumBlock(int verbose = 1, uShort saveData = 0); // saveData = 0 (no save), 1 (no trace), 2 (with trace);
int ReadNextBlock(bool traceON = false, int verbose = 0, uShort saveData = 0); // saveData = 0 (no save), 1 (no trace), 2 (with trace);
int ReadBlock(unsigned int ID, int verbose = 0);
unsigned int GetFilePos() const {return filePos;}
unsigned long GetTotNumBlock() const{ return totNumBlock;}
std::vector<unsigned int> GetBlockTimestamp() const {return blockTimeStamp;}
Data * GetData() const{return data;}
std::string GetFileName() const{return fileName;}
int GetDPPType() const{return DPPType;}
int GetSN() const{return sn;}
int GetTick2ns() const{return tick2ns;}
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();}
ulong GetHitListLength() const {return hit.size();}
std::vector<Hit> GetHitVector() const {return hit;}
void SortHit(int verbose = false);
Hit GetHit(int id) const {
if( id < 0 ) id = hit.size() + id;
return hit[id];
}
void ClearTotalHitCount() {totalHitCount = 0;}
ulong GetTotalHitCount() const{return totalHitCount;}
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, totalHitCount); i++){
printf("%10zu ", i); hit[i].Print();
}
}
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 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);
}
}
void PrintHitListInfo(){
size_t n = hit.size();
size_t s = sizeof(Hit);
printf("============== reader.hit, size : %zu | %.2f MByte\n", n, n*s/1024./1024.);
if( n > 0 ){
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);
}
}
unsigned long GetOptimumBatchSize() const {return optBufferSize;}
private:
FILE * inFile;
Data * data;
std::string fileName;
std::vector<std::string> fileList;
short fileID;
unsigned long inFileSize;
unsigned int filePos;
unsigned long totNumBlock;
unsigned int blockID;
bool isDualBlock;
uShort sn;
uShort DPPType;
uShort tick2ns;
uShort order;
uShort chMask;
uShort numCh;
uShort runNum;
std::vector<unsigned int> blockPos;
std::vector<unsigned int > blockTimeStamp;
unsigned long totalHitCount;
std::vector<Hit> hit;
unsigned int word[1]; /// 4 byte
size_t dummy;
char * buffer;
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;
if( inFile ) fclose(inFile);
}
//^==============================================================
inline FSUReader::FSUReader(){
inFile = nullptr;
data = nullptr;
blockPos.clear();
blockTimeStamp.clear();
hit.clear();
fileList.clear();
fileID = -1;
}
//^==============================================================
inline FSUReader::FSUReader(std::string fileName, uInt dataSize, int verbose){
inFile = nullptr;
data = nullptr;
blockPos.clear();
blockTimeStamp.clear();
hit.clear();
fileList.clear();
fileID = -1;
OpenFile(fileName, dataSize, verbose);
}
//^==============================================================
inline FSUReader::FSUReader(std::vector<std::string> fileList, uInt dataSize, int verbose){
inFile = nullptr;
data = nullptr;
blockPos.clear();
blockTimeStamp.clear();
hit.clear();
//The files are the same DPPType and sn
this->fileList = fileList;
fileID = 0;
OpenFile(fileList[fileID], dataSize, verbose);
}
//^==============================================================
inline void FSUReader::OpenFile(std::string fileName, uInt dataSize, int verbose){
/// File format must be YYY...Y_runXXX_AAA_BBB_TT_CCC.fsu
/// YYY...Y = prefix
/// XXX = runID, 3 digits
/// AAA = board Serial Number, 3 digits
/// BBB = DPPtype, 3 digits
/// TT = tick2ns, any digits
/// CCC = over size index, 3 digits
if( inFile != nullptr ) fclose(inFile);
inFile = fopen(fileName.c_str(), "r");
if( inFile == NULL ){
printf("FSUReader::Cannot open file : %s \n", fileName.c_str());
this->fileName = "";
return;
}
this->fileName = fileName;
fseek(inFile, 0L, SEEK_END);
inFileSize = ftell(inFile);
if(verbose) printf("%s | file size : %ld Byte = %.2f MB\n", fileName.c_str() , inFileSize, inFileSize/1024./1024.);
fseek(inFile, 0L, SEEK_SET);
filePos = 0;
if( fileID > 0 ) return;
totNumBlock = 0;
blockID = 0;
blockPos.clear();
blockTimeStamp.clear();
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);
if( ext.find("fsu") != std::string::npos ) {
if(verbose > 1) printf("It is an raw data *.fsu format\n");
isDualBlock = false;
chMask = -1;
}else{
chMask = atoi(ext.c_str());
isDualBlock = true;
if(verbose > 1) printf("It is a splitted dual block data *.fsu.X format, dual channel mask : %d \n", chMask);
}
std::string fileNameNoExt;
found = fileName.find_last_of(".fsu");
size_t found2 = fileName.find_last_of('/');
if( found2 == std::string::npos ){
fileNameNoExt = fileName.substr(0, found-4);
}else{
fileNameNoExt = fileName.substr(found2+1, found-4);
}
// Split the string by underscores
std::istringstream iss(fileNameNoExt);
std::vector<std::string> tokens;
std::string token;
while (std::getline(iss, token, '_')) { tokens.push_back(token); }
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 ) { 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;
printf("Cannot find DPPType in the filename. Abort.");
return ;
}
numCh = (DPPType == DPPTypeCode::DPP_QDC_CODE ? 64 : 16);
data = new Data(numCh, dataSize);
data->tick2ns = tick2ns;
data->boardSN = sn;
data->DPPType = DPPType;
}
//^==============================================================
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 | hit size : %zu\n", hit.size());
fileID ++;
OpenFile(fileList[fileID], data->GetDataSize(), 1 );
}else{
return -1;
}
}
dummy = fread(word, 4, 1, inFile);
fseek(inFile, -4, SEEK_CUR);
if( dummy != 1) {
printf("fread error, should read 4 bytes, but read %ld x 4 byte, file pos: %ld / %ld byte\n",
dummy, ftell(inFile), inFileSize);
return -10;
}
short header = ((word[0] >> 28 ) & 0xF);
Hit temp;
if( header == 0xA ) { ///normal header
unsigned int aggSize = (word[0] & 0x0FFFFFFF) * 4; ///byte
if( aggSize > inFileSize - ftell(inFile)) aggSize = inFileSize - ftell(inFile);
buffer = new char[aggSize];
dummy = fread(buffer, aggSize, 1, inFile);
filePos = ftell(inFile);
if( dummy != 1) {
printf("fread error, should read %d bytes, but read %ld x %d byte, file pos: %ld / %ld byte \n",
aggSize, dummy, aggSize, ftell(inFile), inFileSize);
return -30;
}
data->DecodeBuffer(buffer, aggSize, !traceON, verbose); // data will own the buffer
//printf(" word Index = %u | filePos : %u | ", data->GetWordIndex(), filePos);
}else if( (header & 0xF ) == 0x8 ) { /// dual channel header
unsigned int dualSize = (word[0] & 0x7FFFFFFF) * 4; ///byte
buffer = new char[dualSize];
dummy = fread(buffer, dualSize, 1, inFile);
filePos = ftell(inFile);
data->buffer = buffer;
data->DecodeDualBlock(buffer, dualSize, DPPType, chMask, !traceON, verbose);
}else{
printf("incorrect header.\n trminate.");
return -20;
}
for( int ch = 0; ch < data->GetNChannel(); ch++){
if( data->NumEventsDecoded[ch] == 0 ) continue;
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;
if( start < 0 ) start = start + data->GetDataSize();
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 ) {
temp.traceLength = data->Waveform1[ch][k].size();
temp.trace = data->Waveform1[ch][k];
}else{
temp.traceLength = 0;
if( temp.trace.size() > 0 ) temp.trace.clear();
}
// temp.Print();
hit.push_back(temp);
}
}
}
data->ClearTriggerRate();
data->ClearNumEventsDecoded();
data->ClearBuffer(); // this will clear the buffer.
return 0;
}
//^==============================================================
inline int FSUReader::ReadBlock(unsigned int ID, int verbose){
if( totNumBlock == 0 )return -1;
if( ID >= totNumBlock )return -1;
data->ClearData();
fseek( inFile, 0L, SEEK_SET);
if( verbose ) printf("Block index: %u, File Pos: %u byte\n", ID, blockPos[ID]);
fseek(inFile, blockPos[ID], SEEK_CUR);
filePos = blockPos[ID];
blockID = ID;
return ReadNextBlock(false, verbose, false);
}
//^==============================================================
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) {
return a.timestamp < b.timestamp;
});
if( verbose) printf(".......done.\n");
}
//^==============================================================
inline void FSUReader::ScanNumBlock(int verbose, uShort saveData){
if( inFile == nullptr ) return;
if( feof(inFile) ) return;
blockID = 0;
blockPos.push_back(0);
data->ClearData();
rewind(inFile);
filePos = 0;
bool isTraceOn = saveData < 2 ? false : true;
while( ReadNextBlock(isTraceOn, verbose - 1, saveData) == 0 ){
blockPos.push_back(filePos);
blockTimeStamp.push_back(data->aggTime);
blockID ++;
if(verbose && blockID % 10000 == 0) printf("%u, %.2f%% %u/%lu\n\033[A\r", blockID, filePos*100./inFileSize, filePos, inFileSize);
}
totNumBlock = blockID;
if(verbose) {
printf("\nScan complete: number of data Block : %lu\n", totNumBlock);
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());
if( saveData ){
size_t sizeT = sizeof(hit[0]) * hit.size();
printf("size of hit array : %lu byte = %.2f kByte, = %.2f MByte\n", sizeT, sizeT/1024., sizeT/1024./1024.);
}
}
if( fileList.size() > 0 ){
fileID = 0;
OpenFile(fileList[fileID], data->GetDataSize(), 0);
}
rewind(inFile);
blockID = 0;
filePos = 0;
//check is the hitCount == hit.size();
if( saveData ){
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 traceOn, bool verbose){
// printf("%s sn:%d. filePos : %lu\n", __func__, sn, ftell(inFile));
std::vector<Hit> hitList_A;
if( IsEndOfFile() ) {
hitList_A = hit;
hit.clear();
return hitList_A;
}
if( hit.size() == 0 ){
int res = 0;
do{
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 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;
hit.clear();
}else{
hitList_A = hit;
hit.clear();
}
if( IsEndOfFile() ) return hitList_A; // when file finished for 1st batch read
int res = 0;
do{
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("dt : %15.3f ms\n", (t1_B - t0_B)/1e6);
}
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("\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> ();
}
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;
// find the hit that is >= t0_B, save them to 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]);
}
// remove hitList_A element that is >= t0_B
hitList_A.erase(hitList_A.begin() + ID_A, hitList_A.end() );
// find the hit that is <= t1_A, save them to hitTemp
for( size_t j = 0; j < hit.size(); j++){
if( hit[j].timestamp > t1_A ) {
break;
}
hitTemp.push_back(hit[j]);
ID_B = j + 1;
}
// remove hit elements that is <= t1_A
hit.erase(hit.begin(), hit.begin() + ID_B );
// sort hitTemp
std::sort(hitTemp.begin(), hitTemp.end(), [](const Hit& a, const Hit& b) {
return a.timestamp < b.timestamp;
});
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();
printf("=========== sume of A + B + Temp : %zu \n", hitList_A.size() + hit.size() + hitTemp.size());
printf("----------------- refill hitList_A \n");
}
for( size_t j = 0; j < hitTemp.size(); j++){
hitList_A.push_back(hitTemp[j]);
}
hitTemp.clear();
if( verbose ) {
PrintHitListInfo(&hitList_A, "hitList_A");
PrintHitListInfo();
printf("=========== sume of A + B : %zu \n", hitList_A.size() + hit.size());
}
}
return hitList_A;
}

View File

@ -1,129 +0,0 @@
#ifndef AGGSEPARATOR_H
#define AGGSEPARATOR_H
#include <stdio.h>
#include <string>
#include <sstream>
#include <cmath>
#include <cstring> ///memset
#include <iostream> ///cout
#include <sstream>
#include <iomanip> // for setw
#include <algorithm>
#include <bitset>
#include <vector>
#include <sys/stat.h>
#define NumCoupledChannel 8 // the max numnber of Coupled/RegChannel is 8 for PHA, PSD, QDC
std::vector<std::string> AggSeperator(std::string inFileName, std::string saveFolder = "./", short verbose = false){
printf("================ AggSeperator \n");
std::vector<std::string> outputFileList;
outputFileList.clear();
FILE * file = fopen(inFileName.c_str(), "r");
if( file == NULL ) {
printf("file : %s cannot be open. exit program.\n", inFileName.c_str());
return outputFileList;
}
std::string folder = "";
size_t found = inFileName.find_last_of('/');
std::string fileName = inFileName;
if( found != std::string::npos ){
folder = inFileName.substr(0, found + 1);
fileName = inFileName.substr(found +1 );
}
if( saveFolder.empty() ) saveFolder = "./";
if( saveFolder.back() != '/') saveFolder += '/';
printf(" fileName : %s \n", fileName.c_str());
printf(" folder : %s \n", folder.c_str());
printf(" save folder : %s\n", saveFolder.c_str());
char * buffer = nullptr;
unsigned int word; // 4 bytes = 32 bits
bool newFileFlag[NumCoupledChannel];
for( int i = 0; i < NumCoupledChannel; i++){
newFileFlag[i] = true;
outputFileList.push_back( saveFolder + fileName + "." + std::to_string(i) + ".agg");
}
do{
size_t dummy = fread(&word, 4, 1, file);
if( dummy != 1 ){
printf("=====> End of File.\n");
break;
}
short header = ((word >> 28 ) & 0xF);
if( header != 0xA ) {
printf("header error. abort.\n");
break;
}
//unsigned int aggSize = (word & 0x0FFFFFFF) * 4; ///byte
dummy = fread(&word, 4, 1, file);
//unsigned int BoardID = ((word >> 27) & 0x1F);
//unsigned short pattern = ((word >> 8 ) & 0x7FFF );
//bool BoardFailFlag = ((word >> 26) & 0x1 );
unsigned int ChannelMask = ( word & 0xFF ) ;
dummy = fread(&word, 4, 1, file);
unsigned int bdAggCounter = word;
if( verbose ) printf("Agg counter : %u\n", bdAggCounter);
dummy = fread(&word, 4, 1, file);
//unsigned int aggTimeTag = word;
for( int chMask = 0; chMask < NumCoupledChannel ; chMask ++ ){
if( ((ChannelMask >> chMask) & 0x1 ) == 0 ) continue;
if( verbose ) printf("==================== Dual/Group Channel Block, ch Mask : 0x%X (%d)\n", chMask *2, chMask );
dummy = fread(&word, 4, 1, file);
unsigned int dualChannelBlockSize = ( word & 0x7FFFFFFF ) * 4 ;
if( verbose ) printf("dual channel size : %d words\n", dualChannelBlockSize / 4);
buffer = new char[dualChannelBlockSize];
fseek(file, -4, SEEK_CUR);
dummy = fread(buffer, dualChannelBlockSize, 1, file);
FILE * haha = nullptr;
if( newFileFlag[chMask] ) {
haha = fopen( outputFileList[chMask].c_str(), "wb");
newFileFlag[chMask] = false;
}else{
haha = fopen( outputFileList[chMask].c_str(), "a+");
}
fwrite(buffer, dualChannelBlockSize, 1, haha);
fclose(haha);
}
}while( !feof(file));
fclose(file);
printf("======================= Duel channels seperated \n");
for( int i = NumCoupledChannel -1 ; i >= 0 ; i--){
if( newFileFlag[i] == true ) outputFileList.erase(outputFileList.begin() + i );
}
return outputFileList;
}
#endif

View File

@ -1,49 +0,0 @@
#ifndef CustomStruct_H
#define CustomStruct_H
#include <string>
#include <vector>
#include <cstdio>
#define ORDERSHIFT 100000
struct FileInfo {
std::string fileName;
unsigned int fileSize;
unsigned int SN;
unsigned long hitCount;
unsigned short DPPType;
unsigned short tick2ns;
unsigned short order;
unsigned short readerID;
unsigned long long t0;
unsigned long ID; // sn + 100000 * order
void CalOrder(){ ID = ORDERSHIFT * SN + order; }
void Print(){
printf(" %10lu | %3d | %60s | %2d | %6lu | %10u Bytes = %.2f MB\n",
ID, DPPType, fileName.c_str(), tick2ns, hitCount, fileSize, fileSize/1024./1024.);
}
};
struct GroupInfo{
std::vector<unsigned short> fileIDList;
unsigned int usedHitCount ;
std::vector<unsigned short> readerIDList;
unsigned long hitID ; // this is the ID for the reader->GetHit(hitID);
unsigned short currentID ; // the ID of the readerIDList;
unsigned long hitCount ; // this is the hitCount for the currentID;
unsigned int sn;
bool finished;
unsigned long long timeShift;
};
#endif

View File

@ -1,319 +0,0 @@
#include "fsuReader.h"
#include "CustomStruct.h"
#include "TROOT.h"
#include "TSystem.h"
#include "TClonesArray.h"
#include "TGraph.h"
#include "TFile.h"
#include "TTree.h"
#include "TMacro.h"
#define MAX_MULTI 1000
//^#############################################################
//^#############################################################
int main(int argc, char **argv) {
printf("=========================================\n");
printf("=== *.fsu Events Builder ===\n");
printf("=========================================\n");
if (argc <= 3) {
printf("Incorrect number of arguments:\n");
printf("%s [timeWindow] [verbose] [inFile1] [inFile2] .... \n", argv[0]);
printf(" timeWindow : in ns \n");
printf(" verbose : > 0 for debug \n");
printf(" Output file name is contructed from inFile1 \n");
printf("\n");
printf("=========================== Working flow\n");
printf(" 1) Load all data into memories as vector and sort\n");
printf(" 2) Build event.\n");
printf("\n\n");
return 1;
}
uInt runStartTime = getTime_us();
///============= read input
unsigned int timeWindow = atoi(argv[1]);
//bool traceOn = atoi(argv[3]);
unsigned int debug = atoi(argv[2]);
int nFile = argc - 3;
TString inFileName[nFile];
for( int i = 0 ; i < nFile ; i++){
inFileName[i] = argv[i+3];
}
/// Form outFileName;
TString outFileName = inFileName[0];
int pos = outFileName.Last('/');
pos = outFileName.Index("_", pos+1); // find next "_", expName
pos = outFileName.Index("_", pos+1); // find next "_", runID
if( nFile == 1 ) pos = outFileName.Index("_", pos+1); // find next "_", S/N
outFileName.Remove(pos); // remove the rest
outFileName += "_" + std::to_string(timeWindow) + "_noTrace";
outFileName += ".root";
printf("-------> Out file name : %s \n", outFileName.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 = %u ns = %.1f us\n", timeWindow, timeWindow/1000.);
//printf(" Buffer size = %.0f event/channel\n", MaxNData * bufferSize);
printf("===================================== input files:\n");
///============= sorting file by the serial number & order
std::vector<FileInfo> fileInfo;
FSUReader ** reader = new FSUReader*[nFile];
// file name format is expName_runID_SN_DPP_tick2ns_order.fsu
for( int i = 0; i < nFile; i++){
printf("Processing %s (%d/%d) ..... \n\033[A\r", inFileName[i].Data(), i+1, nFile);
reader[i] = new FSUReader(inFileName[i].Data(), 600, 0); // the 600 is expecting each agg, there are maximum 1000 hit/ch.
reader[i]->ScanNumBlock(1, 1);
reader[i]->GetData()->ClearDataPointer();
FileInfo tempInfo;
tempInfo.fileName = inFileName[i];
tempInfo.readerID = i;
tempInfo.SN = reader[i]->GetSN();
tempInfo.hitCount = reader[i]->GetTotalHitCount();
tempInfo.fileSize = reader[i]->GetFileByteSize();
tempInfo.tick2ns = reader[i]->GetTick2ns();
tempInfo.DPPType = reader[i]->GetDPPType();
tempInfo.order = reader[i]->GetFileOrder();
tempInfo.CalOrder();
fileInfo.push_back(tempInfo);
}
std::sort(fileInfo.begin(), fileInfo.end(), [](const FileInfo& a, const FileInfo& b) {
return a.ID < b.ID;
});
unsigned int totHitCount = 0;
for( int i = 0 ; i < nFile; i++){
printf("%d |", i);
fileInfo[i].Print();
totHitCount += fileInfo[i].hitCount;
}
printf("----- total number of hit : %u.\n", totHitCount);
//*======================================= Sort files into groups
std::vector<GroupInfo> group;
for( int i = 0; i < nFile; i++){
if( i == 0 || group.back().sn != fileInfo[i].SN ){
group.push_back(GroupInfo());
group.back().readerIDList.push_back(fileInfo[i].readerID); // an empty struct
group.back().currentID = 0;
group.back().hitCount = fileInfo[i].hitCount;
group.back().hitID = 0;
group.back().sn = fileInfo[i].SN;
group.back().finished = false;
}else{
group.back().readerIDList.push_back(fileInfo[i].readerID);
}
}
int nGroup = group.size();
printf("===================================== number of file Group by digitizer %d.\n", nGroup);
for( int i = 0; i < nGroup; i++){
printf(" Digi-%d, DPPType: %d \n", reader[group[i].readerIDList[0]]->GetSN(), reader[group[i].readerIDList[0]]->GetDPPType());
for( int j = 0; j< (int) group[i].readerIDList.size(); j++){
uShort rID = group[i].readerIDList[j];
printf(" %s \n", reader[rID]->GetFileName().c_str());
reader[rID]->PrintHit(10, 0);
}
}
// //*====================================== create tree
TFile * outRootFile = new TFile(outFileName, "recreate");
TTree * tree = new TTree("tree", outFileName);
unsigned long long evID = 0;
unsigned int multi = 0;
unsigned short sn[MAX_MULTI] = {0}; /// board SN
unsigned short ch[MAX_MULTI] = {0}; /// chID
unsigned short e[MAX_MULTI] = {0}; /// 15 bit
unsigned short e2[MAX_MULTI] = {0}; /// 15 bit
unsigned long long e_t[MAX_MULTI] = {0}; /// timestamp 47 bit
unsigned short e_f[MAX_MULTI] = {0}; /// fine time 10 bit
bool pileUp[MAX_MULTI] = {false};
tree->Branch("evID", &evID, "event_ID/l");
tree->Branch("multi", &multi, "multi/i");
tree->Branch("sn", sn, "sn[multi]/s");
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_timestamp[multi]/s");
tree->Branch("pileUp", pileUp, "pileUp[multi]/O");
//TClonesArray * arrayTrace = nullptr;
//unsigned short traceLength[MAX_MULTI] = {0};
//TGraph * trace = nullptr;
// if( traceOn ) {
// arrayTrace = new TClonesArray("TGraph");
// tree->Branch("traceLength", traceLength, "traceLength[multi]/s");
// tree->Branch("trace", arrayTrace, 2560000);
// arrayTrace->BypassStreamer();
// }
//*====================================== build events
printf("================= Building events....\n");
std::vector<Hit> event;
Hit temp;
ullong t0 = -1;
uShort group0 = -1;
uInt hitProcessed = 0;
ullong tStart = 0;
ullong tEnd = 0;
do{
event.clear();
t0 = -1;
/// Find earliest time
for( int gpID = 0; gpID < nGroup; gpID++){
if( group[gpID].finished ) continue;
//when all hit are used, go to next file or make the group.finished = true
if( group[gpID].hitID >= group[gpID].hitCount) {
// printf(" group ID : %d, reader ID : %d is finished. \n", gpID, group[gpID].readerIDList[group[gpID].currentID]);
group[gpID].currentID ++;
if( group[gpID].currentID >= group[gpID].readerIDList.size() ) {
group[gpID].finished = true;
printf("-----> no more file for this group, S/N : %d.\n", group[gpID].sn);
continue;
}else{
group[gpID].hitID = 0;
uShort rID = group[gpID].readerIDList[group[gpID].currentID];
group[gpID].hitCount = reader[rID]->GetTotalHitCount();
printf("-----> go to the next file, %s \n", fileInfo[rID].fileName.c_str() );
}
}
uShort rID = group[gpID].readerIDList[group[gpID].currentID];
ulong hitID = group[gpID].hitID;
ullong t = reader[rID]->GetHit(hitID).timestamp;
if( t < t0 ) {
t0 = t;
group0 = gpID;
}
}
if (debug ) printf("the eariliest time is %llu at Group : %u, hitID : %lu, %s\n", t0, group0, group[group0].hitID, fileInfo[group[group0].currentID].fileName.c_str());
if( hitProcessed % 10000 == 0 ) printf("hit Porcessed %u/%u....%.2f%%\n\033[A\r", hitProcessed, totHitCount, hitProcessed*100./totHitCount);
for(int i = 0; i < nGroup; i++){
uShort gpID = (i + group0) % nGroup;
if( group[gpID].finished ) continue;
uShort rID = group[gpID].readerIDList[group[gpID].currentID];
for( ulong iHit = group[gpID].hitID; iHit < group[gpID].hitCount; iHit ++ ){
if( reader[rID]->GetHit(iHit).timestamp - t0 <= timeWindow ) {
event.push_back(reader[rID]->GetHit(iHit));
group[gpID].hitID ++;
hitProcessed ++;
}else{
break;
}
if( timeWindow == 0 ) break;
}
if( timeWindow == 0 ) break;
}
if( event.size() > 1) {
std::sort(event.begin(), event.end(), [](const Hit& a, const Hit& b) {
return a.timestamp < b.timestamp;
});
}
multi = event.size();
if (debug )printf("########### evID : %llu, multi : %u \n", evID, multi);
if( evID == 0) tStart = event.front().timestamp;
if( multi > 0 ) {
if( hitProcessed >= totHitCount ) tEnd = event.back().timestamp;
for( size_t j = 0; j < multi ; j++){
sn[j] = event[j].sn;
ch[j] = event[j].ch;
e[j] = event[j].energy;
e2[j] = event[j].energy2;
e_t[j] = event[j].timestamp;
e_f[j] = event[j].fineTime;
pileUp[j] = event[j].pileUp;
if (debug )event[j].Print();
}
outRootFile->cd();
tree->Fill();
evID ++;
}
//check if all groups are finished
int gpCount = 0;
for( size_t i = 0; i < group.size(); i++){
if( group[i].finished ) gpCount ++;
}
if( gpCount == (int) group.size() ) {
break;
}
}while(true);
tree->Write();
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 events built = %llu by event builder (%llu in tree)\n", evID, tree->GetEntriesFast());
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());
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 < nFile; i++) delete reader[i];
delete [] reader;
}

View File

@ -1,434 +0,0 @@
#include "fsuReader.h"
#include "fsutsReader.h"
#include "TROOT.h"
#include "TSystem.h"
#include "TClonesArray.h"
#include "TGraph.h"
#include "TFile.h"
#include "TTree.h"
#include "TMacro.h"
#include "CustomStruct.h"
#define MAX_MULTI 1000
//^#############################################################
//^#############################################################
int main(int argc, char **argv) {
printf("=========================================\n");
printf("=== *.fsu Events Builder ===\n");
printf("=========================================\n");
if (argc <= 6) {
printf("Incorrect number of arguments:\n");
printf("%s [timeWindow] [withTrace] [verbose] [tempFolder] [inFile1] [inFile2] .... \n", argv[0]);
printf(" timeWindow : in ns \n");
printf(" withTrace : 0 for no trace, 1 for trace \n");
printf(" verbose : > 0 for debug \n");
printf(" tempFolder : temperary folder for file breakdown \n");
printf(" Output file name is contructed from inFile1 \n");
printf("\n");
printf("=========================== Working flow\n");
printf(" 1) Break down the fsu files into dual channel, save in tempFolder as *.fsu.X\n");
printf(" 1a) if the *.fsu file has trace, *.fsu.ts will also has trace.\n");
printf(" 2) Load the *.fsu.X files and do the event building\n");
printf("\n\n");
return 1;
}
uInt runStartTime = getTime_us();
///============= read input
unsigned int timeWindow = atoi(argv[1]);
bool traceOn = atoi(argv[2]);
unsigned int debug = atoi(argv[3]);
std::string tempFolder = argv[4];
int nFile = argc - 5;
TString inFileName[nFile];
for( int i = 0 ; i < nFile ; i++){ inFileName[i] = argv[i+5];}
/// Form outFileName;
TString outFileName = inFileName[0];
int pos = outFileName.Last('/');
pos = outFileName.Index("_", pos+1); // find next "_"
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());
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 = %u ns = %.1f us\n", timeWindow, timeWindow/1000.);
//printf(" Buffer size = %.0f event/channel\n", MaxNData * bufferSize);
printf("===================================== Breaking down files\n");
///========================================
printf("===================================== Load the files\n");
//check if all input files is ts file;
bool isTSFiles = false;
int count = 0;
for( int i = 0; i < nFile; i++){
FILE * temp = fopen(inFileName[i].Data(), "r");
uint32_t header;
fread(&header, 4, 1, temp);
if( (header >> 24) == 0xAA ) count++;
}
if( count == nFile ) isTSFiles = true;
std::vector<FileInfo> fileInfo;
if( !isTSFiles ){
printf("######### All files are not time-sorted files\n");
///============= sorting file by the serial number & order
FSUReader ** reader = new FSUReader*[nFile];
// file name format is expName_runID_SN_DPP_tick2ns_order.fsu
for( int i = 0; i < nFile; i++){
printf("Processing %s (%d/%d) ..... \n", inFileName[i].Data(), i+1, nFile);
reader[i] = new FSUReader(inFileName[i].Data(), 600, false);
if( !reader[i]->IsOpen() ){
printf("------- cannot open file.\n");
continue;
}
if( reader[i]->GetFileByteSize() == 0 ){
printf("------- file size is ZERO.\n");
continue;
}
reader[i]->ScanNumBlock(false, 2);
std::string outFileName = reader[i]->SaveHit2NewFile(tempFolder);
FileInfo tempInfo;
tempInfo.fileName = outFileName;
tempInfo.readerID = i;
tempInfo.SN = reader[i]->GetSN();
tempInfo.hitCount = reader[i]->GetTotalHitCount();
tempInfo.fileSize = reader[i]->GetTSFileSize();
tempInfo.tick2ns = reader[i]->GetTick2ns();
tempInfo.DPPType = reader[i]->GetDPPType();
tempInfo.order = reader[i]->GetFileOrder();
tempInfo.CalOrder();
tempInfo.t0 = reader[i]->GetHit(0).timestamp;
fileInfo.push_back(tempInfo);
delete reader[i];
}
delete [] reader;
}else{
printf("######### All files are time sorted files\n");
FSUTSReader ** reader = new FSUTSReader*[nFile];
// file name format is expName_runID_SN_DPP_tick2ns_order.fsu
for( int i = 0; i < nFile; i++){
printf("Processing %s (%d/%d) ..... \n", inFileName[i].Data(), i+1, nFile);
reader[i] = new FSUTSReader(inFileName[i].Data(), false);
if( !reader[i]->isOpen() ){
printf("------- cannot open file.\n");
continue;
}
//reader[i]->ScanFile(1);
if( reader[i]->GetNumHitFromHeader() == 0 ){
printf("------- file has no data.\n");
continue;
}
FileInfo tempInfo;
tempInfo.fileName = inFileName[i].Data();
tempInfo.readerID = i;
tempInfo.SN = reader[i]->GetSN();
tempInfo.hitCount = reader[i]->GetNumHitFromHeader();
tempInfo.fileSize = reader[i]->GetFileByteSize();
tempInfo.order = reader[i]->GetFileOrder();
tempInfo.CalOrder();
tempInfo.t0 = reader[i]->GetT0();;
fileInfo.push_back(tempInfo);
delete reader[i];
}
delete [] reader;
}
nFile = (int) fileInfo.size();
std::sort(fileInfo.begin(), fileInfo.end(), [](const FileInfo& a, const FileInfo& b) {
return a.ID < b.ID;
});
unsigned int totHitCount = 0;
printf("===================================== number of file %d.\n", nFile);
for( int i = 0 ; i < nFile; i++){
printf("%d |", i);
fileInfo[i].Print();
totHitCount += fileInfo[i].hitCount;
//printf(" %30s | ID %10ld \n", fileInfo[i].fileName.Data(), fileInfo[i].ID);
}
printf("----- total number of hit : %u.\n", totHitCount);
//*======================================= Sort files into groups
std::vector<GroupInfo> group; // group by SN and chMask
for( int i = 0; i < nFile; i++){
if( i == 0 || group.back().sn != fileInfo[i].SN ){
group.push_back(GroupInfo());
group.back().fileIDList.push_back(i); // an empty struct
group.back().currentID = 0;
group.back().hitCount = fileInfo[i].hitCount;
group.back().sn = fileInfo[i].SN;
group.back().finished = false;
}else{
group.back().fileIDList.push_back(i);
}
}
int nGroup = group.size();
printf("===================================== number of file Group by digitizer %d.\n", nGroup);
for( int i = 0; i < nGroup; i++){
printf(" Digi-%d, DPPType: %d \n", group[i].sn, fileInfo[group[i].currentID].DPPType);
for( int j = 0; j< (int) group[i].fileIDList.size(); j++){
uShort fID = group[i].fileIDList[j];
printf(" %s \n", fileInfo[fID].fileName.c_str());
}
}
// //*====================================== create tree
TFile * outRootFile = new TFile(outFileName, "recreate");
TTree * tree = new TTree("tree", outFileName);
unsigned long long evID = 0;
unsigned int multi = 0;
unsigned short sn[MAX_MULTI] = {0}; /// board SN
unsigned short ch[MAX_MULTI] = {0}; /// chID
unsigned short e[MAX_MULTI] = {0}; /// 15 bit
unsigned short e2[MAX_MULTI] = {0}; /// 15 bit
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];
tree->Branch("evID", &evID, "event_ID/l");
tree->Branch("multi", &multi, "multi/i");
tree->Branch("sn", sn, "sn[multi]/s");
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_timestamp[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();
}
//*======================================= Open time-sorted files
printf("===================================== Open time-sorted files.\n");
FSUTSReader ** tsReader = new FSUTSReader * [nGroup];
for( int i = 0; i < nGroup; i++){
std::string fileName = fileInfo[group[i].fileIDList[0]].fileName;
tsReader[i] = new FSUTSReader(fileName);
// tsReader[i]->ScanFile(1);
group[i].usedHitCount = 0;
}
//*====================================== build events
printf("================= Building events....\n");
uInt hitProcessed = 0;
//find the earliest time
ullong t0 = -1;
uShort gp0 = -1;
ullong tStart = 0;
ullong tEnd = 0;
bool hasEvent = false;
for( int i = 0; i < nGroup; i++){
if( fileInfo[group[i].fileIDList[0]].t0 < t0 ) {
t0 = fileInfo[group[i].fileIDList[0]].t0;
gp0 = i;
}
}
if( debug ) printf("First timestamp is %llu, group : %u\n", t0, gp0);
do{
if( debug ) printf("################################ ev build %llu \n", evID);
///===================== check if the file is finished.
for( int i = 0; i < nGroup; i++){
uShort gpID = (i + gp0) % nGroup;
if( group[gpID].finished ) continue;
short endCount = 0;
do{
if( group[gpID].usedHitCount > tsReader[gpID]->GetHitID() || tsReader[gpID]->GetFilePos() <= 4){
if( tsReader[gpID]->ReadNextHit(traceOn, 0) == 0 ){
hitProcessed ++;
if( debug ){ printf("............ Get Data | "); tsReader[gpID]->GetHit()->Print();}
}
}
if( tsReader[gpID]->GetHit()->timestamp - t0 <= timeWindow ) {
if( evID == 0) tStart = tsReader[gpID]->GetHit()->timestamp;
if( hitProcessed >= totHitCount ) tEnd = tsReader[gpID]->GetHit()->timestamp;
sn[multi] = tsReader[gpID]->GetHit()->sn;
ch[multi] = tsReader[gpID]->GetHit()->ch;
e[multi] = tsReader[gpID]->GetHit()->energy;
e2[multi] = tsReader[gpID]->GetHit()->energy2;
e_t[multi] = tsReader[gpID]->GetHit()->timestamp;
e_f[multi] = tsReader[gpID]->GetHit()->fineTime;
traceLength[multi] = tsReader[gpID]->GetHit()->traceLength;
if( traceOn ){
trace = (TGraph *) arrayTrace->ConstructedAt(multi, "C");
trace->Clear();
for( int hh = 0; hh < traceLength[multi]; hh++){
trace->SetPoint(hh, hh, tsReader[gpID]->GetHit()->trace[hh]);
}
}
if( debug ) printf("(%5d, %2d) %6d %16llu, %u\n", sn[multi], ch[multi], e[multi], e_t[multi], traceLength[multi]);
hasEvent = true;
multi ++;
group[gpID].usedHitCount ++;
if( tsReader[gpID]->ReadNextHit(traceOn, 0) == 0 ){
hitProcessed ++;
if( debug ){ printf("..Get Data after fill | "); tsReader[gpID]->GetHit()->Print();}
}
if( multi > MAX_MULTI) {
printf(" !!!!!! multi > MAX_MULTI = %d\n", MAX_MULTI);
}
}else{
break;
}
if( timeWindow == 0) break;
if( tsReader[gpID]->GetHitID() + 1 >= tsReader[gpID]->GetNumHitFromHeader() ) endCount ++;
if( endCount == 2 ) break;
}while(true);
}
if( hasEvent ){
outRootFile->cd();
tree->Fill();
multi = 0;
evID ++;
hasEvent = false;
}
if( hitProcessed % 10000 == 0 ) printf("hit Porcessed %u/%u hit....%.2f%%\n\033[A\r", hitProcessed, totHitCount, hitProcessed*100./totHitCount);
///===================== find the next first timestamp
t0 = -1;
gp0 = -1;
for( int i = 0; i < nGroup; i++) {
if( group[i].finished ) continue;
if( tsReader[i]->GetHit()->timestamp < t0) {
t0 = tsReader[i]->GetHit()->timestamp;
gp0 = i;
}
}
if( debug ) printf("Next First timestamp is %llu, group : %u\n", t0, gp0);
///===================== check if the file is finished.
int gpCount = 0;
for( int gpID = 0; gpID < nGroup; gpID ++) {
if( group[gpID].finished ) {
gpCount ++;
continue;
}
if( group[gpID].usedHitCount >= tsReader[gpID]->GetNumHitFromHeader() ) {
group[gpID].currentID ++;
if( group[gpID].currentID >= group[gpID].fileIDList.size() ) {
group[gpID].finished = true;
printf("-----> no more file for this group, S/N : %d.\n", group[gpID].sn);
}else{
uShort fID = group[gpID].fileIDList[group[gpID].currentID];
std::string fileName = fileInfo[fID].fileName;
delete tsReader[gpID];
tsReader[gpID] = new FSUTSReader(fileName);
tsReader[gpID]->ScanFile(1);
printf("-----> go to the next file, %s \n", fileName.c_str() );
group[gpID].usedHitCount = 0;
}
}
if( group[gpID].finished ) gpCount ++;
}
if( gpCount == (int) group.size() ) break;
}while(true);
tree->Write();
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 events built = %llu by event builder (%llu in tree)\n", evID, tree->GetEntriesFast());
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());
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 tsReader[i];
}
delete [] tsReader;
return 0;
}

View File

@ -1,471 +0,0 @@
#include "../ClassData.h"
#include "../MultiBuilder.h"
#include "fsuReader.h"
#include "TROOT.h"
#include "TSystem.h"
#include "TClonesArray.h"
#include "TGraph.h"
#include "TFile.h"
#include "TTree.h"
#define MAX_MULTI 100
#define TIMEJUMP 1e8 // 0.1 sec or 10 Hz, any signal less than 10 Hz should increase the value.
template<typename T> void swap(T * a, T *b );
int partition(int arr[], int kaka[], TString file[], unsigned int fileSize[], unsigned int numBlock[], int t2ns[], int start, int end);
void quickSort(int arr[], int kaka[], TString file[], unsigned int fileSize[], unsigned int numBlock[], int t2ns[], int start, int end);
//^#############################################################
//^#############################################################
int main(int argc, char **argv) {
printf("=========================================\n");
printf("=== *.fsu Events Builder ===\n");
printf("=========================================\n");
if (argc <= 3) {
printf("Incorrect number of arguments:\n");
printf("%s [timeWindow] [Buffer] [traceOn/Off] [verbose] [inFile1] [inFile2] .... \n", argv[0]);
printf(" timeWindow : in ns \n");
printf(" Buffer : Fraction of %d, recommand 0.4 \n", DefaultDataSize);
printf(" traceOn/Off : is traces stored \n");
printf(" verbose : > 0 for debug \n");
printf(" Output file name is contructed from inFile1 \n");
printf("\n");
printf(" * there is a TIMEJUMP = 1e8 ns in EventBuilder.cpp.\n");
printf(" This control the time diff for a time jumping.\n");
printf(" Any signal with trigger rate < 1/TIMEJUMP should increase the value.\n");
return 1;
}
/// File format must be YYY...Y_runXXX_AAA_BBB_TT_CCC.fsu
/// YYY...Y = prefix
/// XXX = runID, 3 digits
/// AAA = board Serial Number, 3 digits
/// BBB = DPPtype, 3 digits
/// TT = tick2ns, any digits
/// CCC = over size index, 3 digits
///============= read input
unsigned int timeWindow = atoi(argv[1]);
float bufferSize = atof(argv[2]);
bool traceOn = atoi(argv[3]);
unsigned int debug = atoi(argv[4]);
int nFile = argc - 5;
TString inFileName[nFile];
for( int i = 0 ; i < nFile ; i++){
inFileName[i] = argv[i+5];
}
/// Form outFileName;
TString outFileName = inFileName[0];
int pos = outFileName.Index("_");
pos = outFileName.Index("_", pos+1);
outFileName.Remove(pos);
outFileName += ".root";
printf("-------> Out file name : %s \n", outFileName.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 = %u ns = %.1f us\n", timeWindow, timeWindow/1000.);
printf(" Buffer size = %.0f event/channel\n", DefaultDataSize * bufferSize);
printf("===================================== input files:\n");
printf("Scanning files.....\n");
///============= sorting file by the serial number & order
int ID[nFile]; /// serial+ order*1000;
int type[nFile];
unsigned int fileSize[nFile];
unsigned int numBlock[nFile];
int tick2ns[nFile];
// file name format is expName_runID_SN_DPP_tick2ns_order.fsu
for( int i = 0; i < nFile; i++){
FSUReader * reader = new FSUReader(inFileName[i].Data(), false);
reader->ScanNumBlock(false);
numBlock[i] = reader->GetTotNumBlock();
fileSize[i] = reader->GetFileByteSize();
tick2ns[i] = reader->GetTick2ns();
type[i] = reader->GetDPPType();
int sn = reader->GetSN();
int order = reader->GetFileOrder();
ID[i] = sn + order * 100000;
delete reader;
}
quickSort(&(ID[0]), &(type[0]), &(inFileName[0]), &(fileSize[0]), &(numBlock[0]), &(tick2ns[0]), 0, nFile-1);
unsigned int totBlock = 0;
for( int i = 0 ; i < nFile; i++){
printf("%d | %6d | %3d | %30s | %2d | %6u | %u Bytes = %.2f MB\n", i,
ID[i], type[i], inFileName[i].Data(), tick2ns[i], numBlock[i], fileSize[i], fileSize[i]/1024./1024.);
totBlock += numBlock[i];
}
printf("----- total number of block : %u.\n", totBlock);
//*======================================= Sort files into groups
std::vector<int> snList; // store the serial number of the group
std::vector<int> typeList; // store the DPP type of the group
std::vector<std::vector<TString>> fileList; // store the file list of the group
std::vector<int> t2nsList;
for( int i = 0; i < nFile; i++){
if( ID[i] / 100000 == 0 ) {
std::vector<TString> temp = {inFileName[i]};
fileList.push_back(temp);
typeList.push_back(type[i]);
snList.push_back(ID[i]%100000);
t2nsList.push_back(tick2ns[i]);
}else{
for( int p = 0; p < (int) snList.size(); p++){
if( (ID[i] % 1000) == snList[p] ) {
fileList[p].push_back(inFileName[i]);
}
}
}
}
int nGroup = snList.size();
printf("===================================== number of file Group by digitizer %d.\n", nGroup);
for( int i = 0; i < nGroup; i++){
printf("............ Digi-%d \n", snList[i]);
for( int j = 0; j< (int) fileList[i].size(); j++){
printf(" %s | %d\n", fileList[i][j].Data(), typeList[i]);
}
}
//*======================================= open raw files
printf("##############################################\n");
/// for each detector, open it
std::vector<int> inFileIndex(nGroup); // the index of the the opened file for each group
FILE ** inFile = new FILE *[nGroup];
Data ** data = new Data *[nGroup];
for( int i = 0; i < nGroup; i++){
inFile[i] = fopen(fileList[i][0], "r");
if( inFile[i] ){
inFileIndex[i] = 0;
if( typeList[i] == DPPTypeCode::DPP_PHA_CODE || typeList[i] == DPPTypeCode::DPP_PSD_CODE ) data[i] = new Data(16);
if( typeList[i] == DPPTypeCode::DPP_QDC_CODE ) data[i] = new Data(64);
data[i]->DPPType = typeList[i];
data[i]->boardSN = snList[i];
data[i]->tick2ns = t2nsList[i];
}else{
inFileIndex[i] = -1;
data[i] = nullptr;
}
}
//*====================================== create tree
TFile * outRootFile = new TFile(outFileName, "recreate");
TTree * tree = new TTree("tree", outFileName);
unsigned long long evID = -1;
unsigned short multi = 0;
unsigned short sn[MAX_MULTI] = {0}; /// board SN
unsigned short ch[MAX_MULTI] = {0}; /// chID
unsigned short e[MAX_MULTI] = {0}; /// 15 bit
unsigned short e2[MAX_MULTI] = {0}; /// 15 bit
unsigned long long e_t[MAX_MULTI] = {0}; /// timestamp 47 bit
unsigned short e_f[MAX_MULTI] = {0}; /// fine time 10 bit
tree->Branch("evID", &evID, "event_ID/l");
tree->Branch("multi", &multi, "multi/s");
tree->Branch("sn", sn, "sn[multi]/s");
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_timestamp[multi]/s");
TClonesArray * arrayTrace = nullptr;
unsigned short traceLength[MAX_MULTI] = {0};
TGraph * trace = nullptr;
if( traceOn ) {
arrayTrace = new TClonesArray("TGraph");
tree->Branch("traceLength", traceLength, "traceLength[multi]/s");
tree->Branch("trace", arrayTrace, 2560000);
arrayTrace->BypassStreamer();
}
//*====================================== build events
printf("================= Building events....\n");
MultiBuilder * mb = new MultiBuilder(data, typeList, snList);
mb->SetTimeWindow(timeWindow);
mb->SetTimeJump(TIMEJUMP);
///------------------ read data
char * buffer = nullptr;
unsigned int word[1]; // 4 byte = 32 bit
int lastDataIndex[nGroup][MAX_MULTI]; // keep track of the DataIndex
int lastLoopIndex[nGroup][MAX_MULTI]; // keep track of the LoopIndex
int aggCount[nGroup];
for( int i = 0; i < nGroup; i++){
aggCount[i] = 0;
for( int j = 0; j < MAX_MULTI; j++){
lastDataIndex[i][j] = 0;
lastLoopIndex[i][j] = 0;
}
}
do{
/// fill the data class with some agg;
bool fillFlag = true;
do{
// Get many agg. from each file.
for ( int i = 0; i < nGroup; i++){
if( inFile[i] == nullptr ) continue;
size_t dummy = fread(word, 4, 1, inFile[i]);
if( dummy != 1) {
//printf("fread error, should read 4 bytes, but read %ld x 4 byte, file pos: %ld byte (%s)\n", dummy, ftell(inFile[i]), fileList[i][inFileIndex[i]].Data());
// go to next file in same digitizer
if( feof(inFile[i])){
fclose(inFile[i]);
if( inFileIndex[i] + 1 < (int) fileList[i].size() ){
inFile[i] = fopen(fileList[i][inFileIndex[i]+1], "r");
inFileIndex[i]++;
printf("---- go to next file for digi-%d\n", snList[i]);
}else{
inFile[i] = nullptr;
inFileIndex[i] = -1;
printf("---- no more file for digi-%d.\n", snList[i]);
continue;
}
// if( inFile[i] ){
// inFileIndex[i]++;
// printf("---- go to next file for digi-%d\n", snList[i]);
// }else{
// inFileIndex[i] = -1;
// printf("---- no more file for digi-%d.\n", snList[i]);
// continue;
// }
}
}else{
fseek(inFile[i], -4, SEEK_CUR); // roll back
short header = ((word[0] >> 28 ) & 0xF);
if( header != 0xA ) break;
unsigned int aggSize = (word[0] & 0x0FFFFFFF) * 4; ///byte
buffer = new char[aggSize];
size_t dummy2 = fread(buffer, aggSize, 1, inFile[i]);
if( dummy2 != 1) {
printf("fread error, should read %d bytes, but read %ld x %d byte, file pos: %ld byte (%s)\n", aggSize, dummy, aggSize, ftell(inFile[i]), fileList[i][inFileIndex[i]].Data());
}else{
data[i]->DecodeBuffer(buffer, aggSize, false, 0);
data[i]->ClearBuffer();
aggCount[i] ++;
}
}
}
//if all file exhausted, break
int okFileNum = 0;
for( int i = 0; i < nGroup; i++){
if( inFileIndex[i] != -1 ) okFileNum ++;
}
if( okFileNum == 0 ) break;
//check if Data Index near MaxNData. if near by 50%, break
//printf("-----------------------------------\n");
for( int i = 0; i < nGroup; i++){
if( debug ){
printf("-------------------------> %3d | agg : %d | %u \n", snList[i], aggCount[i], data[i]->aggTime);
//data[i]->PrintStat();
}
uShort dataSize = data[i]->GetDataSize();
for( int ch = 0; ch < data[i]->GetNChannel(); ch ++){
int iData = data[i]->DataIndex[ch];
int iLoop = data[i]->LoopIndex[ch];
if( iData < 0 ) continue;
if( (iLoop*dataSize + iData) - (lastLoopIndex[i][ch]*dataSize + lastDataIndex[i][ch]) > dataSize * bufferSize ) {
if( debug ) printf("############# BREAK!!!! Group: %d, ch : %d | last : %d(%d), Present : %d(%d) | BufferSize : %.0f \n", i, ch, lastDataIndex[i][ch], lastLoopIndex[i][ch], iData, iLoop, dataSize * bufferSize);
fillFlag = false;
}
if( debug ){
unsigned long long t1 = data[i]->Timestamp[ch][iData];
printf("digi:%5d | ch: %2d DataIndex: %5d (%d) [%5d(%d)] | %16llu\n", data[i]->boardSN, ch, iData, iLoop, lastDataIndex[i][ch], lastLoopIndex[i][ch], t1);
}
}
}
}while(fillFlag);
for( int i = 0; i < nGroup; i++){
for( int ch = 0; ch < data[i]->GetNChannel(); ch ++){
lastDataIndex[i][ch] = data[i]->DataIndex[ch];
lastLoopIndex[i][ch] = data[i]->LoopIndex[ch];
}
//data[i]->PrintAllData();
}
mb->BuildEvents(0, !traceOn, debug);
if( debug ) mb->PrintStat();
///----------- save to tree;
long startIndex = mb->eventIndex - mb->eventBuilt + 1;
//printf("startIndex : %6ld -> %6ld, %6ld, %6ld, %ld | %llu\n", startIndex, startIndex < 0 ? startIndex + MaxNEvent : startIndex, mb->eventIndex, mb->eventBuilt, mb->totalEventBuilt, tree->GetEntries());
if (startIndex < 0 ) startIndex += MaxNEvent;
for( long p = startIndex; p < startIndex + mb->eventBuilt; p++){
int k = p % MaxNEvent;
multi = mb->events[k].size();
if( multi > MAX_MULTI) {
printf("!!!!! MAX_MULTI %d reached.\n", MAX_MULTI);
break;
}
evID ++;
for( int j = 0; j < multi; j ++){
sn[j] = mb->events[k][j].sn;
ch[j] = mb->events[k][j].ch;
e[j] = mb->events[k][j].energy;
e2[j] = mb->events[k][j].energy2;
e_t[j] = mb->events[k][j].timestamp;
e_f[j] = mb->events[k][j].fineTime;
if( traceOn ){
traceLength[j] = mb->events[k][j].trace.size();
trace = (TGraph *) arrayTrace->ConstructedAt(j, "C");
trace->Clear();
for( int hh = 0; hh < traceLength[j]; hh++){
trace->SetPoint(hh, hh, mb->events[k][j].trace[hh]);
}
}
}
outRootFile->cd();
tree->Fill();
}
int okFileNum = 0;
for( int i = 0; i < nGroup; i++){
if( inFileIndex[i] != -1 ) okFileNum ++;
}
if( okFileNum == 0 ) break;
}while(true);
if( timeWindow >= 0 ){
printf("------------------- build the last data\n");
mb->BuildEvents(1, 0, debug);
//mb->PrintStat();
///----------- save to tree;
long startIndex = mb->eventIndex - mb->eventBuilt + 1;
//printf("startIndex : %ld -> %ld, %ld, %ld, %ld\n", startIndex, startIndex < 0 ? startIndex + MaxNEvent : startIndex, mb->eventIndex, mb->eventBuilt, mb->totalEventBuilt);
if( startIndex < 0 ) startIndex += MaxNEvent;
for( long p = startIndex; p < startIndex + mb->eventBuilt; p++){
int k = p % MaxNEvent;
multi = mb->events[k].size();
if( multi > MAX_MULTI) {
printf("!!!!! MAX_MULTI %d reached.\n", MAX_MULTI);
break;
}
evID ++;
for( int j = 0; j < multi; j ++){
sn[j] = mb->events[k][j].sn;
ch[j] = mb->events[k][j].ch;
e[j] = mb->events[k][j].energy;
e2[j] = mb->events[k][j].energy2;
e_t[j] = mb->events[k][j].timestamp;
e_f[j] = mb->events[k][j].fineTime;
if( traceOn ){
traceLength[j] = mb->events[k][j].trace.size();
trace = (TGraph *) arrayTrace->ConstructedAt(j, "C");
trace->Clear();
for( int hh = 0; hh < traceLength[j]; hh++){
trace->SetPoint(hh, hh, mb->events[k][j].trace[hh]);
}
}
}
outRootFile->cd();
tree->Fill();
}
}
tree->Write();
printf("========================= finished.\n");
printf("total events built = %llu(%llu)\n", evID + 1, tree->GetEntriesFast());
printf("=======> saved to %s \n", outFileName.Data());
outRootFile->Close();
delete mb;
for( int i = 0 ; i < nGroup; i++) delete data[i];
delete [] data;
}
//^#############################################################
//^#############################################################
template<typename T> void swap(T * a, T *b ){
T temp = * b;
*b = *a;
*a = temp;
}
int partition(int arr[], int kaka[], TString file[], unsigned int fileSize[], unsigned int numBlock[], int tick2ns[], int start, int end){
int pivot = arr[start];
int count = 0;
for (int i = start + 1; i <= end; i++) {
if (arr[i] <= pivot) count++;
}
/// Giving pivot element its correct position
int pivotIndex = start + count;
swap(&arr[pivotIndex], &arr[start]);
swap(&file[pivotIndex], &file[start]);
swap(&kaka[pivotIndex], &kaka[start]);
swap(&fileSize[pivotIndex], &fileSize[start]);
swap(&numBlock[pivotIndex], &numBlock[start]);
swap(&tick2ns[pivotIndex], &tick2ns[start]);
/// Sorting left and right parts of the pivot element
int i = start, j = end;
while (i < pivotIndex && j > pivotIndex) {
while (arr[i] <= pivot) {i++;}
while (arr[j] > pivot) {j--;}
if (i < pivotIndex && j > pivotIndex) {
int ip = i++;
int jm = j--;
swap( &arr[ip], &arr[jm]);
swap(&file[ip], &file[jm]);
swap(&kaka[ip], &kaka[jm]);
swap(&fileSize[ip], &fileSize[jm]);
swap(&numBlock[ip], &numBlock[jm]);
swap(&tick2ns[ip], &tick2ns[jm]);
}
}
return pivotIndex;
}
void quickSort(int arr[], int kaka[], TString file[], unsigned int fileSize[], unsigned int numBlock[], int tick2ns[], int start, int end){
/// base case
if (start >= end) return;
/// partitioning the array
int p = partition(arr, kaka, file, fileSize, numBlock, tick2ns, start, end);
/// Sorting the left part
quickSort(arr, kaka, file, fileSize, numBlock, tick2ns, start, p - 1);
/// Sorting the right part
quickSort(arr, kaka, file, fileSize, numBlock, tick2ns, p + 1, end);
}

View File

@ -1,241 +0,0 @@
#include "../Hit.h"
#include "../macro.h"
#include <stdio.h>
#include <string>
#include <sstream>
#include <cmath>
#include <cstring> ///memset
#include <iostream> ///cout
#include <sstream>
#include <algorithm>
#include <bitset>
#include <vector>
class FSUTSReader{
public:
FSUTSReader();
FSUTSReader(std::string fileName, int verbose = 1);
~FSUTSReader();
void OpenFile(std::string fileName, int verbose = 1);
bool isOpen() const{return inFile == nullptr ? false : true;}
void ScanFile(int verbose = 1);
int ReadNextHit(bool withTrace = true, int verbose = 0);
int ReadHitAt(unsigned int ID, bool withTrace = true, int verbose = 0);
unsigned int GetHitID() const {return hitIndex;}
unsigned long GetNumHit() const {return hitCount;}
unsigned long GetNumHitFromHeader() const {return hitCount0;}
std::string GetFileName() const {return fileName;}
unsigned long GetFileByteSize() const {return inFileSize;}
unsigned int GetFilePos() const {return filePos;}
int GetFileOrder() const {return order;}
uShort GetSN() const {return sn;}
ullong GetT0() const {return t0;}
Hit* GetHit() const{return hit;}
private:
FILE * inFile;
std::string fileName;
unsigned long inFileSize;
unsigned int filePos;
unsigned long hitCount;
unsigned long hitCount0; // hit count from file
uShort sn;
int order;
Hit* hit;
unsigned int hitIndex;
std::vector<unsigned int> hitStartPos;
unsigned long long t0;
uint32_t header;
size_t dummy;
};
inline FSUTSReader::~FSUTSReader(){
fclose(inFile);
delete hit;
}
inline FSUTSReader::FSUTSReader(){
inFile = nullptr;
hitStartPos.clear();
hit = nullptr;
}
inline FSUTSReader::FSUTSReader(std::string fileName, int verbose){
OpenFile(fileName, verbose);
}
inline void FSUTSReader::OpenFile(std::string fileName, int verbose){
inFile = fopen(fileName.c_str(), "r");
if( inFile == NULL ){
printf("FSUTSReader::Cannot open file : %s \n", fileName.c_str());
this->fileName = "";
return;
}
this->fileName = fileName;
std::string fileNameNoExt;
size_t found = fileName.find_last_of(".fsu.ts");
size_t found2 = fileName.find_last_of('/');
if( found2 == std::string::npos ){
fileNameNoExt = fileName.substr(0, found-7);
}else{
fileNameNoExt = fileName.substr(found2+1, found-7);
}
// Split the string by underscores
std::istringstream iss(fileNameNoExt);
std::vector<std::string> tokens;
std::string token;
while (std::getline(iss, token, '_')) { tokens.push_back(token); }
sn = atoi(tokens[2].c_str());
order = atoi(tokens[5].c_str());
fseek(inFile, 0L, SEEK_END);
inFileSize = ftell(inFile);
if(verbose) printf("###### %50s | %11ld Byte = %.2f MB\n", fileName.c_str() , inFileSize, inFileSize/1024./1024.);
fseek(inFile, 0L, SEEK_SET);
filePos = 0;
hitCount = 0;
hitIndex = -1;
hitStartPos.clear();
hit = new Hit();
hit->Clear();
//check is the file is .ts file by checking the 1st 4 byte
dummy = fread(&header, 4, 1, inFile);
printf(" header : 0x%8X.", header);
if( (header >> 24) != 0xAA ){
printf(" This is not a time-sorted fsu (*.fsu.ts) file. Abort.");
return;
}
sn = (header & 0xFFFFFF);
hit->sn = sn;
printf(" S/N : %u, ", sn);
dummy = fread(&hitCount0, 8, 1, inFile);
printf(" hitCount : %lu \n", hitCount0);
}
inline int FSUTSReader::ReadNextHit(bool withTrace, int verbose){
if( inFile == NULL ) return -1;
if( feof(inFile) ) return -1;
if( filePos >= inFileSize) return -1;
hitIndex ++;
hit->sn = sn;
uint16_t temp = 0;
dummy = fread(&temp, 2, 1, inFile); // [0:7] ch [8] pileUp [14] hasTrace [15] hasEnergy2
hit->ch = (temp & 0xFF);
hit->pileUp = ((temp>>8) & 0x1);
bool hasEnergy2 = ((temp>>15) & 0x1);
bool hasTrace = ((temp>>14) & 0x1);
dummy = fread(&(hit->energy), 2, 1, inFile);
if( hasEnergy2 ) dummy = fread(&(hit->energy2), 2, 1, inFile);
dummy = fread(&(hit->timestamp), 6, 1, inFile);
dummy = fread(&(hit->fineTime), 2, 1, inFile);
if( hasTrace ) {
dummy = fread(&(hit->traceLength), 2, 1, inFile);
if( hit->trace.size() > 0 ) hit->trace.clear();
}
if( withTrace && hit->traceLength > 0 ){
for(uShort j = 0; j < hit->traceLength; j++){
short temp;
fread( &temp, 2, 1, inFile);
hit->trace.push_back(temp);
}
}else{
unsigned int jumpByte = hit->traceLength * 2;
fseek(inFile, jumpByte, SEEK_CUR);
hit->traceLength = 0;
}
filePos = ftell(inFile);
// if(verbose) printf("Block index: %u, current file Pos: %u byte \n", hitIndex, filePos);
if(verbose >= 2) hit->Print();
if(verbose >= 3) hit->PrintTrace();
return 0;
}
inline int FSUTSReader::ReadHitAt(unsigned int ID, bool withTrace, int verbose){
if( hitCount == 0 ) return -1;
if( ID >= hitCount ) return -1;
fseek(inFile, 0L, SEEK_SET);
if( verbose ) printf("Block index: %u, File Pos: %u byte\n", ID, hitStartPos[ID]);
fseek(inFile, hitStartPos[ID], SEEK_CUR);
filePos = hitStartPos[ID];
hitIndex = ID - 1;
return ReadNextHit(withTrace, verbose);
}
inline void FSUTSReader::ScanFile(int verbose){
if( feof(inFile) ) return;
hitStartPos.clear();
fseek(inFile, 0L, SEEK_SET);
dummy = fread(&header, 4, 1, inFile);
dummy = fread(&hitCount0, 8, 1, inFile);
filePos = ftell(inFile);
hitStartPos.push_back(filePos);
hitIndex = -1;
while( ReadNextHit(false, verbose-1) == 0 ){ // no trace
hitStartPos.push_back(filePos);
if( hitIndex == 0 ) t0 = hit->timestamp;
if(verbose > 1 ) printf("hitIndex : %u, Pos : %u - %u\n" , hitIndex, hitStartPos[hitIndex], hitStartPos[hitIndex+1]);
if(verbose && hitIndex%10000 == 0 ) printf(" %u, %.2f%% %u/%lu byte \n\033[A\r", hitIndex, filePos*100./inFileSize, filePos, inFileSize);
}
hitCount = hitIndex + 1;
if(verbose) {
printf("\n-----> Scan complete\n");
printf(" number of hit : %lu\n", hitCount);
printf(" first timestamp : %16llu\n", t0);
printf(" last timestamp : %16llu\n", hit->timestamp);
double dt = (hit->timestamp - t0)*1e-9;
printf(" duration : %.2f sec = %.2f min\n", dt, dt/60.);
}
fseek(inFile, 0L, SEEK_SET);
fseek(inFile, hitStartPos[0], SEEK_CUR);
filePos = hitStartPos[0];
hitIndex = -1;
}

View File

@ -1,30 +0,0 @@
#!/bin/bash
if [ $# -eq 0 ]; then
echo "Usage: $0 file_pattern"
echo "example:"
echo " $0 \"test_002*.fsu\""
exit 1
fi
file_pattern="$1"
# Iterate through each file in the directory
for file in ${file_pattern}; do
echo ${file}
if [[ $file == *QDC* ]]; then
# Insert "16" before the last underscore
new_name="${file%_*}_16_${file##*_}"
else
# Insert "4" before the last underscore
new_name="${file%_*}_4_${file##*_}"
fi
# Rename the file
mv -iv "$file" "$new_name"
echo "Renamed: $file to $new_name"
done

View File

@ -1,114 +0,0 @@
#include "fsuReader.h"
// #include "../MultiBuilder.cpp"
#include "SplitPolePlotter.C"
#include "SplitPolePlotter_MT.C"
void script(){
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");
// 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?
SplotPolePlotter_MT(chain, 5, pidCut, 123.307, 2.75, true);
//^=====================================================
// 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);
// data->ClearData();
// data->ClearTriggerRate();
// 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->PrintStat();
// data->PrintAllData();
// //mb->BuildEvents(true);
// mb->BuildEventsBackWard(300);
// mb->PrintAllEvent();
// mb->PrintStat();
// delete mb;
// delete reader;
}

View File

@ -1,495 +0,0 @@
#include "../macro.h"
#include "../ClassData.h"
#include "../ClassDigitizer.h"
#include "../MultiBuilder.h"
#include "../ClassInfluxDB.h"
#include "ClassDigitizerAPI.h"
#include <TROOT.h>
#include <TSystem.h>
#include <TApplication.h>
#include <TCanvas.h>
#include <TGraph.h>
#include <TH1.h>
#include <TFile.h>
#include <TTree.h>
#include <sys/time.h> /** struct timeval, select() */
#include <termios.h> /** tcgetattr(), tcsetattr() */
#include <vector>
#include <regex>
#include <CAENVMElib.h>
#include <time.h>
static struct termios g_old_kbd_mode;
static void cooked(void);
static void uncooked(void);
static void raw(void);
int keyboardhit();
int getch(void);
#include <curl/curl.h>
size_t WriteCallBack(char *contents, size_t size, size_t nmemb, void *userp){
// printf(" InfluxDB::%s \n", __func__);
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
void testInflux(){
InfluxDB * influx = new InfluxDB();
influx->SetURL("https://fsunuc.physics.fsu.edu/influx/");
//influx->SetURL("http://128.186.111.5:8086/");
influx->SetToken("wS-Oy17bU99qH0cTPJ-Q5tbiOWfaKyoASUx7WwmdM7KG8EJ1BpRowYkqpnPw8oeatnDaZfZtwIFT0kv_aIOAxQ==");
influx->TestingConnection();
influx->CheckDatabases();
influx->PrintDataBaseList();
// printf("=-------------------------\n");
// influx->TestingConnection(true);
printf("%s \n", influx->Query("testing", "show measurements").c_str());
// printf("%s \n", influx->Query("testing", "SELECT * from haha ORDER by time DESC LIMIT 5").c_str());
delete influx;
// CURL *curl = curl_easy_init();
// CURLcode res;
// struct curl_slist * headers = nullptr;
// headers = curl_slist_append(headers, "Authorization: Token wS-Oy17bU99qH0cTPJ-Q5tbiOWfaKyoASUx7WwmdM7KG8EJ1BpRowYkqpnPw8oeatnDaZfZtwIFT0kv_aIOAxQ==");
// // // headers = curl_slist_append(headers, "Content-Type: text/plain; charset=utf-8");
// headers = curl_slist_append(headers, "Accept: application/csv");
// printf("%s\n",headers->data);
// printf("%s\n", headers->next->data);
// curl_slist_free_all(headers);
// // printf("%p \n",headers);
// headers = curl_slist_append(headers, "Accept: application/csv");
// printf("%s\n",headers->data);
// curl_easy_setopt(curl, CURLOPT_POST, 1);
// curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
// std::string databaseIP = "https://fsunuc.physics.fsu.edu/influx/";
// std::string databaseIP = "http://128.186.111.5:8086/";
//*===================== Check version
// curl_easy_setopt(curl, CURLOPT_URL, (databaseIP + "ping").c_str());
// curl_easy_setopt(curl, CURLOPT_HEADER, 1);
//*===================== Query data
//=============== query databases
// curl_easy_setopt(curl, CURLOPT_URL, (databaseIP + "query").c_str());
// std::string postFields="q=Show databases";
//=============== query measurement
// curl_easy_setopt(curl, CURLOPT_URL, (databaseIP + "query?db=testing").c_str());
// std::string postFields="q=SELECT * FROM \"haha\"";
//=============== write measurement
// curl_easy_setopt(curl, CURLOPT_URL, (databaseIP + "write?db=testing").c_str());
// std::string postFields = "haha,BD=1 state=2.345";
// postFields += "\n";
// postFields += "haha,BD=2 state=9.876";
// postFields += "\n";
// curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, static_cast<long>(postFields.length()));
// curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postFields.c_str());
// curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallBack);
// std::string readBuffer;
// curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
// // //curl_easy_setopt(curl, CURLOPT_URL, "https://fsunuc.physics.fsu.edu/influx/api/v2/write?org=FSUFoxLab&bucket=testing");
// res = curl_easy_perform(curl);
// long respondCode;
// curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &respondCode);
// printf("respond code : %ld \n", respondCode);
// if( res == CURLE_OK ) {
// printf("================respond \n%s\n", readBuffer.c_str());
// }else{
// printf("=========== curl_easy_perform fail.\n");
// }
// curl_slist_free_all(headers);
// curl_easy_cleanup(curl);
// std::regex pattern(R"(X-Influxdb-Version: (.*))");
// std::smatch match;
// if (regex_search(readBuffer, match, pattern)) {
// // Extract and print the version
// std::string version = match[1];
// unsigned short vno = -1;
// size_t dotPosition = version.find('.');
// if( dotPosition != std::string::npos){
// vno = atoi(version.substr(dotPosition-1, 1).c_str());
// }
// printf("%s | %d\n", version.c_str(), vno);
// }
//============================================= end of influxDB example
}
void CheckBufferSize(int MaxAggPreRead, int EvtPreAgg){
//Buffer depends on
Digitizer * digi = new Digitizer(0, 26006, false, true);
digi->Reset();
digi->ProgramBoard();
digi->WriteRegister(DPP::SoftwareClear_W, 1);
digi->SetBits(DPP::BoardConfiguration, DPP::Bit_BoardConfig::RecordTrace, 0, -1);
digi->WriteRegister(DPP::RecordLength_G, 10, -1);
digi->SetBits(DPP::BoardConfiguration, DPP::Bit_BoardConfig::EnableExtra2, 1, -1);
digi->WriteRegister(DPP::MaxAggregatePerBlockTransfer, MaxAggPreRead);
digi->WriteRegister(DPP::NumberEventsPerAggregate_G, EvtPreAgg);
unsigned int bufferSize = digi->CalByteForBuffer(true);
unsigned int bufferSizeCAEN = digi->CalByteForBufferCAEN();
printf("Manual Buffer Size : %u Byte = %u words\n", bufferSize, bufferSize/4);
printf(" CAEN Buffer Size : %u Byte = %u words\n", bufferSizeCAEN, bufferSizeCAEN/4);
unsigned int haha = bufferSize*2 + 16 *( 1- MaxAggPreRead );
printf("---- %u %u \n", haha, haha/4);
delete digi;
}
void GetOneAgg(){
Digitizer * digi = new Digitizer(0, 26006, false, true);
if( digi->IsConnected() ){
digi->Reset();
digi->ProgramBoard();
digi->WriteRegister(DPP::SoftwareClear_W, 1);
digi->SetBits(DPP::BoardConfiguration, DPP::Bit_BoardConfig::RecordTrace, 0, -1);
digi->WriteRegister(DPP::RecordLength_G, 10, -1);
digi->SetBits(DPP::BoardConfiguration, DPP::Bit_BoardConfig::EnableExtra2, 1, -1);
digi->WriteRegister(DPP::MaxAggregatePerBlockTransfer, 1);
digi->WriteRegister(DPP::NumberEventsPerAggregate_G, 2);
unsigned int bufferSize = digi->CalByteForBuffer(true);
unsigned int bufferSizeCAEN = digi->CalByteForBufferCAEN();
printf("Manual Buffer Size : %u Byte = %u words\n", bufferSize, bufferSize/4);
printf(" CAEN Buffer Size : %u Byte = %u words\n", bufferSizeCAEN, bufferSizeCAEN/4);
digi->StartACQ();
usleep(5000*1000); // wait 1sec
digi->ReadData();
digi->GetData()->DecodeBuffer(false, 4);
digi->StopACQ();
}
delete digi;
}
void TestVME(){
int ret = -1;
char SWRel[100];
ret = CAENVME_SWRelease(SWRel);
printf("ret = %d | Software release : %s\n", ret, SWRel);
short ConnetNode = 0;
uint32_t link = 0;
int32_t handle;
ret = CAENVME_Init2(cvPCIE_A5818_V3718, &link, ConnetNode, &handle);
printf("ret = %d \n", ret);
// ret = CAENVME_DeviceReset(handle); // only for A2818, A2719, and V2718
// printf("ret = %d \n", ret);
char FWRel[100];
ret = CAENVME_BoardFWRelease(handle, FWRel);
printf("ret = %d | Firmware release : %s\n", ret, FWRel);
char DrRel[100];
ret = CAENVME_DriverRelease(handle, DrRel);
printf("ret = %d | Driver release : %s\n", ret, DrRel);
CVVMETimeouts timeoutValue = CVVMETimeouts::cvTimeout50us;
ret = CAENVME_SetTimeout(handle, timeoutValue);
printf("ret = %d \n", ret);
ret = CAENVME_GetTimeout(handle, &timeoutValue);
printf("ret = %d | timeout : %d\n", ret, timeoutValue);
// ret = CAENVME_ReadRegister(
ret = CAENVME_End(handle);
printf("ret = %d \n", ret);
}
int TestDigitizerRaw(){
int handle;
int ret = CAEN_DGTZ_OpenDigitizer(CAEN_DGTZ_OpticalLink, 0, 0, 0, &handle);
if( ret != 0 ) {
printf("==== open digitizer fail.\n");
printf("=========== close Digitizer \n");
CAEN_DGTZ_SWStopAcquisition(handle);
CAEN_DGTZ_CloseDigitizer(handle);
return 0;
}
CAEN_DGTZ_BoardInfo_t BoardInfo;
ret = (int) CAEN_DGTZ_GetInfo(handle, &BoardInfo);
printf("Connected to Model %s with handle %d\n", BoardInfo.ModelName, handle);
printf(" Family Code : %d \n", BoardInfo.FamilyCode);
printf("No. of Input Channels : %d \n", BoardInfo.Channels);
printf(" SerialNumber : %d \n", BoardInfo.SerialNumber);
printf(" ADC bit : %d \n", BoardInfo.ADC_NBits);
printf(" ROC FPGA Release : %s \n", BoardInfo.ROC_FirmwareRel);
printf(" AMC FPGA Release : %s \n", BoardInfo.AMC_FirmwareRel);
timespec ta, tb;
long long duration;
uint32_t value;
clock_gettime(CLOCK_REALTIME, &ta);
ret = CAEN_DGTZ_WriteRegister(handle, 0x8034, 3);
clock_gettime(CLOCK_REALTIME, &tb);
printf("ret = %d \n", ret);
duration = tb.tv_nsec - ta.tv_nsec;
printf("duration = %lld ns\n", duration);
clock_gettime(CLOCK_REALTIME, &ta);
ret = CAEN_DGTZ_ReadRegister(handle, 0x1034, &value);
clock_gettime(CLOCK_REALTIME, &tb);
printf("ret = %d \n", ret);
duration = tb.tv_nsec - ta.tv_nsec;
printf("duration = %lld ns | value = %u\n", duration, value);
printf("=========== close Digitizer \n");
CAEN_DGTZ_SWStopAcquisition(handle);
CAEN_DGTZ_CloseDigitizer(handle);
return 0;
}
void SimpleDAQ(){
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);
Data * data = digi->GetData();
data->OpenSaveFile("haha2");
digi->StartACQ();
for( int i = 0; i < 10 ; i++ ){
usleep(500*1000);
digi->ReadData();
data->DecodeBuffer(true, 0);
data->SetDecimationFactor(3);
data->SaveData();
data->PrintStat();
}
digi->StopACQ();
}
void Compare_CAEN_Decoder(){
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;
}
//*********************************
//*********************************
static void cooked(void){
tcsetattr(0, TCSANOW, &g_old_kbd_mode);
}
static void uncooked(void){
struct termios new_kbd_mode;
/** put keyboard (stdin, actually) in raw, unbuffered mode */
tcgetattr(0, &g_old_kbd_mode);
memcpy(&new_kbd_mode, &g_old_kbd_mode, sizeof(struct termios));
new_kbd_mode.c_lflag &= ~(ICANON | ECHO);
new_kbd_mode.c_cc[VTIME] = 0;
new_kbd_mode.c_cc[VMIN] = 1;
tcsetattr(0, TCSANOW, &new_kbd_mode);
}
static void raw(void){
static char init;
if(init) return;
/** put keyboard (stdin, actually) in raw, unbuffered mode */
uncooked();
/** when we exit, go back to normal, "cooked" mode */
atexit(cooked);
init = 1;
}
int keyboardhit(){
struct timeval timeout;
fd_set read_handles;
int status;
raw();
/** check stdin (fd 0) for activity */
FD_ZERO(&read_handles);
FD_SET(0, &read_handles);
timeout.tv_sec = timeout.tv_usec = 0;
status = select(0 + 1, &read_handles, NULL, NULL, &timeout);
if(status < 0){
printf("select() failed in keyboardhit()\n");
exit(1);
}
return (status);
}
int getch(void){
unsigned char temp;
raw();
/** stdin = fd 0 */
if(read(0, &temp, 1) != 1) return 0;
return temp;
}

120
CanvasClass.cpp Normal file
View File

@ -0,0 +1,120 @@
#include "CanvasClass.h"
#include <QValueAxis>
#include <QRandomGenerator>
#include <QGroupBox>
#include <QStandardItemModel>
#include <QLabel>
#include <QRandomGenerator>
Canvas::Canvas(Digitizer ** digi, unsigned int nDigi, QMainWindow * parent) : QMainWindow(parent){
this->digi = digi;
this->nDigi = nDigi;
setWindowTitle("Canvas");
setGeometry(0, 0, 1000, 800);
//setWindowFlags( this->windowFlags() & ~Qt::WindowCloseButtonHint );
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);
QPushButton * bnClearHist = new QPushButton("Clear Hist.", this);
ctrlLayout->addWidget(bnClearHist, 0, 0);
connect(bnClearHist, &QPushButton::clicked, this, [=](){
for( int i = 0; i < MaxNDigitizer; i++){
for( int j = 0; j < MaxNChannels; j++){
if( hist[i][j] ) hist[i][j]->Clear();
}
}
});
cbDigi = new RComboBox(this);
for( unsigned int i = 0; i < nDigi; i++) cbDigi->addItem("Digi-" + QString::number( digi[i]->GetSerialNumber() ), i);
ctrlLayout->addWidget(cbDigi, 1, 0);
connect( cbDigi, &RComboBox::currentIndexChanged, this, &Canvas::ChangeHistView);
cbCh = new RComboBox(this);
for( int i = 0; i < MaxNChannels; i++) cbCh->addItem("ch-" + QString::number( i ), i);
ctrlLayout->addWidget(cbCh, 1, 1);
connect( cbCh, &RComboBox::currentIndexChanged, this, &Canvas::ChangeHistView);
//========================
histBox = new QGroupBox("Histgrams", this);
layout->addWidget(histBox);
histLayout = new QGridLayout(histBox);
histBox->setLayout(histLayout);
double xMax = 4000;
double xMin = 0;
double nBin = 100;
for( unsigned int i = 0; i < MaxNDigitizer; i++){
for( int j = 0; j < MaxNChannels; j++){
if( i < nDigi ) {
hist[i][j] = new Histogram("Digi-" + QString::number(digi[i]->GetSerialNumber()) +", Ch-" + QString::number(j), xMin, xMax, nBin);
histView[i][j] = new TraceView(hist[i][j]->GetTrace());
histView[i][j]->SetVRange(0, 10);
}else{
hist[i][j] = nullptr;
}
}
}
histLayout->addWidget(histView[0][0], 0, 0);
oldBd = -1;
oldCh = -1;
}
Canvas::~Canvas(){
for( int i = 0; i < MaxNDigitizer; i++){
for( int j = 0; j < MaxNChannels; j++){
if( hist[i][j] ) {
delete hist[i][j];
delete histView[i][j];
}
}
}
}
void Canvas::ChangeHistView(){
if( oldCh >= 0 ) {
histLayout->removeWidget(histView[oldBd][oldCh]);
histView[oldBd][oldCh]->setParent(nullptr);
}
int bd = cbDigi->currentIndex();
int ch = cbCh->currentIndex();
histLayout->addWidget(histView[bd][ch], 0, 0);
oldBd = bd;
oldCh = ch;
}
void Canvas::UpdateCanvas(){
for( int i = 0; i < nDigi; i++){
digiMTX[i].lock();
for( int ch = 0; ch < digi[i]->GetNChannels(); ch ++ ){
int lastIndex = digi[i]->GetData()->EventIndex[ch];
int nDecoded = digi[i]->GetData()->NumEventsDecoded[ch];
for( int j = lastIndex - nDecoded + 1; j <= lastIndex; j ++){
hist[i][ch]->Fill( digi[i]->GetData()->Energy[ch][j]);
}
}
digiMTX[i].unlock();
}
}

59
CanvasClass.h Normal file
View File

@ -0,0 +1,59 @@
#ifndef CANVAS_H
#define CANVAS_H
#include <QMainWindow>
#include <QChart>
#include <QChartView>
#include <QSpinBox>
#include <QLabel>
#include <QPushButton>
#include <QCheckBox>
#include <QLineEdit>
#include <QComboBox>
#include <QGridLayout>
#include <QGroupBox>
#include <QLineSeries>
#include <QRubberBand>
#include <QMouseEvent>
#include <QGestureEvent>
#include "macro.h"
#include "ClassDigitizer.h"
#include "CustomThreads.h"
#include "CustomWidgets.h"
//^====================================================
//^====================================================
class Canvas : public QMainWindow{
Q_OBJECT
public:
Canvas(Digitizer ** digi, unsigned int nDigi, QMainWindow * parent = nullptr);
~Canvas();
public slots:
void UpdateCanvas();
void ChangeHistView();
private:
Digitizer ** digi;
unsigned short nDigi;
Histogram * hist[MaxNDigitizer][MaxNChannels];
TraceView * histView[MaxNDigitizer][MaxNChannels];
RComboBox * cbDivision;
RComboBox * cbDigi;
RComboBox * cbCh;
QGroupBox * histBox;
QGridLayout * histLayout;
int oldBd, oldCh;
};
#endif

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -27,23 +27,15 @@ class Digitizer{
int portID; /// port ID for optical link for using PCIe card, from 0, 1, 2, 3
int boardID; /// board identity
int handle; /// i don't know why, but better separete the handle from boardID
int NumInputCh; /// number of physical input channel
int NumRegChannel; /// number of Register channel
bool isInputChEqRegCh; /// is number of physical input channel = Register channel
int NCoupledCh; /// number of Coupled channel
int NChannel; /// number of channel
int ADCbits; /// ADC bit
int DPPType; /// DPP verion
int ModelType; /// VME or DT
unsigned int ADCFullSize; /// pow(2, ADCbits) - 1
float tick2ns; /// channel to ns
unsigned int MemorySizekSample; /// channel Memory size in kSample
std::string familyName;
float ch2ns; /// channel to ns
CAEN_DGTZ_BoardInfo_t BoardInfo;
//^----- adjustable parameters
bool softwareDisable; /// not using the whole board
uint32_t regChannelMask ; /// the channel mask from NumInputCh
uint32_t channelMask ; /// the channel mask from NChannel
uint32_t VMEBaseAddress; /// For direct USB or Optical-link connection, VMEBaseAddress must be 0
CAEN_DGTZ_ConnectionType LinkType; /// USB or Optic
CAEN_DGTZ_IOLevel_t IOlev; /// TTL signal (1 = 1.5 to 5V, 0 = 0 to 0.7V ) or NIM signal (1 = -1 to -0.8V, 0 = 0V)
@ -57,10 +49,8 @@ class Digitizer{
//^-------- setting
std::string settingFileName; ///
FILE * settingFile; ///
bool isSettingFileExist; ///
bool isSettingFileUpdate;
bool settingFileExist; ///
bool isSettingFilledinMemeory; /// false for disabled ReadAllSettingFromBoard()
bool hasOverThresholdWidth; /// for QDC
unsigned int setting[SETTINGSIZE]; /// Setting, 4bytes x 2048 = 8192 bytes
//^-------- other protected functions
@ -68,16 +58,6 @@ class Digitizer{
uint32_t returnData;
uint32_t acqStatus;
int ProgramBoard_PHA() ; /// program a default PHA board with dual trace
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);
@ -86,23 +66,18 @@ class Digitizer{
//^------ portID is for optical link for using PCIe card, from 0, 1, 2, 3
int OpenDigitizer(int boardID, int portID = 0, bool program = false, bool verbose = false);
void SetDPPType (int type) { this->DPPType = type;} /// for manual override, or, digitizer does not open
void SetRegChannelMask (uint32_t mask);
void SetRegChannelOnOff (unsigned short ch, bool onOff);
void SetChannelMask (uint32_t mask);
void SetChannelOnOff (unsigned short ch, bool onOff);
int CloseDigitizer();
void Initalization();
void Reset();
bool IsDummy() {return isDummy;}
bool IsConnected() {return isConnected;}
void DisableBoard() {softwareDisable = true;}
void EnableBoard() {softwareDisable = false;}
bool IsBoardDisabled() const {return softwareDisable;}
void PrintBoard();
void ProgramBoard();
void ProgramChannel(short chOrGroup);
void AutoSetDPPEventAggregation();
void PrintBoard() ;
virtual int ProgramBoard() ; /// program a generic board, no program channel
int ProgramPHABoard() ; /// program a default PHA board with dual trace
int ProgramPSDBoard() ;
//^================ ACQ control
void StopACQ();
@ -110,16 +85,9 @@ class Digitizer{
int ReadData();
bool IsRunning() const {return AcqRun;}
Data * GetData() const {return data;}
uint32_t GetACQStatusFromMemory() const {return acqStatus;}
void ReadAndPrintACQStatue();
void ReadACQStatus() { // Only use when ACQ is running;
// printf("%s\n", __func__);
//acqStatus = ReadRegister(DPP::AcquisitionStatus_R);
CAEN_DGTZ_ReadRegister(handle, DPP::AcquisitionStatus_R, &acqStatus);
}
void PrintACQStatue();
unsigned int CalByteForBuffer(bool verbose = false);
unsigned int CalByteForBufferCAEN();
unsigned int CalByteForBuffer();
//^================= Settings
/// write value to digitizer, memory, and settingFile (if exist)
@ -135,25 +103,18 @@ class Digitizer{
CAEN_DGTZ_BoardInfo_t GetBoardInfo() const {return BoardInfo;}
std::string GetModelName() const {return BoardInfo.ModelName;}
int GetSerialNumber() const {return BoardInfo.SerialNumber;}
int GetRegChannelMask() { regChannelMask = GetSettingFromMemory(DPP::RegChannelEnableMask); return regChannelMask;}
bool GetInputChannelOnOff(unsigned ch) ;
float GetTick2ns() const {return tick2ns;}
int GetNumInputCh() const {return NumInputCh;}
int GetNumRegChannels() const {return NumRegChannel;}
bool IsInputChEqRegCh() const {return isInputChEqRegCh;}
int GetCoupledChannels() const {return NCoupledCh;}
int GetChannelMask() { channelMask = GetSettingFromMemory(DPP::ChannelEnableMask); return channelMask;}
bool GetChannelOnOff(unsigned ch) { channelMask = GetSettingFromMemory(DPP::ChannelEnableMask); return (channelMask & ( 1 << ch) );}
float GetCh2ns() const {return ch2ns;}
int GetNChannels() const {return NChannel;}
int GetHandle() const {return handle;}
int GetDPPType() const {return DPPType;}
int GetModelType() const {return ModelType;}
std::string GetDPPString(int DPPType = 0); /// if no input, use digitizer DPPType
int GetADCBits() const {return BoardInfo.ADC_NBits;}
std::string GetROCVersion() const {return BoardInfo.ROC_FirmwareRel;}
std::string GetAMCVersion() const {return BoardInfo.AMC_FirmwareRel;}
CAEN_DGTZ_ConnectionType GetLinkType() const {return LinkType;}
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);
@ -164,15 +125,11 @@ class Digitizer{
/// simply read settings from memory
void SetSettingToMemory (Reg registerAddress, unsigned int value, unsigned short ch = 0);
unsigned int GetSettingFromMemory (Reg registerAddress, unsigned short ch = 0);
unsigned int * GetSettings() {return setting;}
void PrintSettingFromMemory();
void SetSettingFileUpdate(bool onOff) {isSettingFileUpdate = onOff;}
bool IsSettingFileUpdate() const {return isSettingFileUpdate;}
bool IsSettingFileExist() const {return isSettingFileExist;}
void PrintSettingFromMemory ();
unsigned int * GetSettings() {return setting;};
/// memory <--> file
void SaveAllSettingsAsText (std::string fileName);
void SaveAllSettingsAsTextForRun (std::string fileName);
void SaveAllSettingsAsBin (std::string fileName);
std::string GetSettingFileName() {return settingFileName;}
/// tell the digitizer where to look at the setting file.
@ -192,16 +149,43 @@ class Digitizer{
static unsigned int ExtractBits(uint32_t value, std::pair<unsigned short, unsigned short> bit){ return ((value >> bit.second) & uint(pow(2, bit.first)-1) ); }
//====== Board Config breakDown
// bool IsEnabledAutoDataFlush() {return ( GetSettingFromMemory(DPP::BoardConfiguration) & 0x1 );}
// bool IsDecimateTrace() {return ( (GetSettingFromMemory(DPP::BoardConfiguration) >> 1) & 0x1 );}
// bool IsTriggerPropagate() {return ( (GetSettingFromMemory(DPP::BoardConfiguration) >> 2) & 0x1 );}
bool IsDualTrace_PHA() {return ( (GetSettingFromMemory(DPP::BoardConfiguration) >> 11) & 0x1 );}
// unsigned short AnaProbe1Type() {return ( (GetSettingFromMemory(DPP::BoardConfiguration) >> 12) & 0x3 );}
// unsigned short AnaProbe2Type() {return ( (GetSettingFromMemory(DPP::BoardConfiguration) >> 14) & 0x3 );}
bool IsRecordTrace() {return ( (GetSettingFromMemory(DPP::BoardConfiguration) >> 16) & 0x1 );}
// bool IsEnabledExtra2() {return ( (GetSettingFromMemory(DPP::BoardConfiguration) >> 17) & 0x1 );}
// bool IsRecordTimeStamp() {return ( (GetSettingFromMemory(DPP::BoardConfiguration) >> 18) & 0x1 );}
// bool IsRecordEnergy() {return ( (GetSettingFromMemory(DPP::BoardConfiguration) >> 19) & 0x1 );}
// unsigned short DigiProbe1Type() {return ( (GetSettingFromMemory(DPP::BoardConfiguration) >> 20) & 0xF );}
// unsigned short DigiProbe2Type() {return ( (GetSettingFromMemory(DPP::BoardConfiguration) >> 26) & 0x7 );}
//QDC read recordLength
uint32_t ReadQDCRecordLength();
void SetQDCOptimialAggOrg();
// //====== DPP Algorithm Contol breakdown
// unsigned short TrapReScaling(int ch) {return ( (GetSettingFromMemory(DPP::DPPAlgorithmControl, ch) >> 0) & 0x1F );}
// unsigned short TraceDecimation(int ch) {return ( (GetSettingFromMemory(DPP::DPPAlgorithmControl, ch) >> 8) & 0x3 );}
// unsigned short TraceDecimationGain(int ch) {return ( (GetSettingFromMemory(DPP::DPPAlgorithmControl, ch) >> 10) & 0x3 );}
// unsigned short PeakMean(int ch) {return ( (GetSettingFromMemory(DPP::DPPAlgorithmControl, ch) >> 12) & 0x3 );}
// unsigned short Polarity(int ch) {return ( (GetSettingFromMemory(DPP::DPPAlgorithmControl, ch) >> 16) & 0x1 );}
// unsigned short TriggerMode(int ch) {return ( (GetSettingFromMemory(DPP::DPPAlgorithmControl, ch) >> 18) & 0x3 );}
// unsigned short BaseLineAvg(int ch) {return ( (GetSettingFromMemory(DPP::DPPAlgorithmControl, ch) >> 18) & 0x7 );}
// unsigned short DisableSelfTrigger(int ch) {return ( (GetSettingFromMemory(DPP::DPPAlgorithmControl, ch) >> 24) & 0x1 );}
// unsigned short EnableRollOverFlag(int ch) {return ( (GetSettingFromMemory(DPP::DPPAlgorithmControl, ch) >> 26) & 0x1 );}
// unsigned short EnablePileUpFlag(int ch) {return ( (GetSettingFromMemory(DPP::DPPAlgorithmControl, ch) >> 27) & 0x1 );}
// //====== DPP Algorithm Contol 2 breakdown
// unsigned short LocalShapeMode(int ch) {return ( (GetSettingFromMemory(DPP::PHA::DPPAlgorithmControl2_G, ch) >> 0) & 0x7 );}
// unsigned short LocalTrigValidMode(int ch) {return ( (GetSettingFromMemory(DPP::PHA::DPPAlgorithmControl2_G, ch) >> 4) & 0x7 );}
// unsigned short Extra2Option(int ch) {return ( (GetSettingFromMemory(DPP::PHA::DPPAlgorithmControl2_G, ch) >> 8) & 0x3 );}
// unsigned short VetoSource(int ch) {return ( (GetSettingFromMemory(DPP::PHA::DPPAlgorithmControl2_G, ch) >> 14) & 0x3 );}
// unsigned short TrigCounter(int ch) {return ( (GetSettingFromMemory(DPP::PHA::DPPAlgorithmControl2_G, ch) >> 16) & 0x3 );}
// unsigned short ActiveBaseLineCal(int ch) {return ( (GetSettingFromMemory(DPP::PHA::DPPAlgorithmControl2_G, ch) >> 18) & 0x1 );}
// unsigned short TagCorrelatedEvents(int ch) {return ( (GetSettingFromMemory(DPP::PHA::DPPAlgorithmControl2_G, ch) >> 19) & 0x1 );}
// unsigned short OptimizeBaseLineRestorer(int ch) {return ( (GetSettingFromMemory(DPP::PHA::DPPAlgorithmControl2_G, ch) >> 29) & 0x1 );}
//====== Acquistion Control vreakdown
void SetTrace(bool onOff){
SetBits(DPP::BoardConfiguration, DPP::Bit_BoardConfig::RecordTrace, onOff, -1);
}
};

View File

@ -1,283 +0,0 @@
#include "ClassInfluxDB.h"
#include "macro.h"
#include <regex>
InfluxDB::InfluxDB(){
DebugPrint("%s", "InfluxDB");
curl = curl_easy_init();
databaseIP = "";
respondCode = 0;
dataPoints = "";
headers = nullptr;
influxVersionStr = "";
influxVersion = -1;
token = "";
connectionOK = false;
}
InfluxDB::InfluxDB(std::string url, bool verbose){
DebugPrint("%s", "InfluxDB");
curl = curl_easy_init();
if( verbose) curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
SetURL(url);
respondCode = 0;
dataPoints = "";
headers = nullptr;
influxVersionStr = "";
influxVersion = -1;
token = "";
connectionOK = false;
}
InfluxDB::~InfluxDB(){
DebugPrint("%s", "InfluxDB");
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
}
void InfluxDB::SetURL(std::string url){
DebugPrint("%s", "InfluxDB");
// check the last char of url is "/"
if( url.back() != '/') {
this->databaseIP = url + "/";
}else{
this->databaseIP = url;
}
}
void InfluxDB::SetToken(std::string token){
DebugPrint("%s", "InfluxDB");
this->token = token;
headers = curl_slist_append(headers, "Accept: application/csv");
if( !token.empty() ) headers = curl_slist_append(headers, ("Authorization: Token " + token).c_str());
}
bool InfluxDB::TestingConnection(bool debug){
DebugPrint("%s", "InfluxDB");
CheckInfluxVersion(debug);
if( respond != CURLE_OK ) return false;
connectionOK = true;
return true;
}
std::string InfluxDB::CheckInfluxVersion(bool debug){
DebugPrint("%s", "InfluxDB");
curl_easy_setopt(curl, CURLOPT_URL, (databaseIP + "ping").c_str());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, NULL);
curl_easy_setopt(curl, CURLOPT_HEADER, 1);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallBack);
std::string respondStr;
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &respondStr);
Execute();
if( respond != CURLE_OK) return "CURL Error.";
if( debug) printf("%s\n", respondStr.c_str());
//Find Version from readBuffer
std::regex pattern(R"(X-Influxdb-Version: (.*))");
std::smatch match;
if (regex_search(respondStr, match, pattern)) {
influxVersionStr = match[1];
size_t dotPosition = influxVersionStr.find('.');
if( dotPosition != std::string::npos){
influxVersion = atoi(influxVersionStr.substr(dotPosition-1, 1).c_str());
}
}
// printf("Influx Version : %s | %u\n", influxVersionStr.c_str(), influxVersion);
return respondStr;
}
std::string InfluxDB::CheckDatabases(){
DebugPrint("%s", "InfluxDB");
if( ! connectionOK ) return "no connection. try TestConnection() again.";
if( influxVersion == 2 && token.empty() ) return "token no provided, abort.";
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_HEADER, 0);
curl_easy_setopt(curl, CURLOPT_URL, (databaseIP + "query").c_str());
std::string postFields="q=Show databases";
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, static_cast<long>(postFields.length()));
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postFields.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallBack);
std::string respondStr;
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &respondStr);
Execute();
// printf("|%s|\n", respondStr.c_str());
if( respond != CURLE_OK) return "CURL Error.";
databaseList.clear();
// Split the input string into lines
std::istringstream iss(respondStr);
std::vector<std::string> lines;
std::string line;
while (std::getline(iss, line)) {
lines.push_back(line);
}
// Extract the third column from each line and store it in a vector
std::vector<std::string> thirdColumn;
for (const auto& l : lines) {
std::istringstream lineIss(l);
std::string token;
for (int i = 0; std::getline(lineIss, token, ','); ++i) {
if (i == 2) { // Third column
databaseList.push_back(token);
break;
}
}
}
// {//============ when output is JSON
// size_t pos = readBuffer.find("values");
// if( pos > 0 ){
// std::string kaka = readBuffer.substr(pos+8);
// pos = kaka.find("}");
// kaka = kaka.substr(0, pos);
// int len = kaka.length();
// bool startFlag = false;
// std::string lala;
// char yaya = '"';
// for( int i = 0; i < len; i++){
// if( startFlag == false && kaka[i] == yaya ) {
// startFlag = true;
// lala = "";
// continue;
// }
// if( startFlag && kaka[i] == yaya ){
// startFlag = false;
// databaseList.push_back(lala);
// continue;
// }
// if( startFlag ) lala += kaka[i];
// }
// }
// }
return respondStr;
}
void InfluxDB::PrintDataBaseList(){
DebugPrint("%s", "InfluxDB");
for( size_t i = 0; i < databaseList.size(); i++){
printf("%2ld| %s\n", i, databaseList[i].c_str());
}
}
std::string InfluxDB::Query(std::string databaseName, std::string influxQL_query){
DebugPrint("%s", "InfluxDB");
if( ! connectionOK ) return "no connection. try TestConnection() again.";
if( influxVersion == 2 && token.empty() ) return "token no provided, abort.";
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_HEADER, 0);
curl_easy_setopt(curl, CURLOPT_URL, (databaseIP + "query?db=" + databaseName).c_str());
std::string postFields = "q=" + influxQL_query;
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, static_cast<long>(postFields.length()));
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postFields.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallBack);
std::string respondStr;
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &respondStr);
Execute();
//printf("|%s|\n", readBuffer.c_str());
return respondStr;
}
void InfluxDB::CreateDatabase(std::string databaseName){
DebugPrint("%s", "InfluxDB");
if( ! connectionOK ) return ;
if( influxVersion == 2 && token.empty() ) return;
curl_easy_setopt(curl, CURLOPT_URL, (databaseIP + "query").c_str());
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_HEADER, 0);
std::string postFields = "q=CREATE DATABASE " + databaseName;
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, static_cast<long>(postFields.length()));
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postFields.c_str());
Execute();
}
void InfluxDB::AddDataPoint(std::string fullString){
DebugPrint("%s", "InfluxDB");
// printf(" InfluxDB::%s |%s| \n", __func__, fullString.c_str());
dataPoints += fullString + "\n";
}
void InfluxDB::ClearDataPointsBuffer(){
DebugPrint("%s", "InfluxDB");
// printf(" InfluxDB::%s \n", __func__);
dataPoints = "";
}
void InfluxDB::PrintDataPoints(){
DebugPrint("%s", "InfluxDB");
// printf(" InfluxDB::%s \n", __func__);
printf("%s\n", dataPoints.c_str());
}
void InfluxDB::WriteData(std::string databaseName){
DebugPrint("%s", "InfluxDB");
if( ! connectionOK ) return ;
if( influxVersion == 2 && token.empty() ) return;
// printf(" InfluxDB::%s \n", __func__);
if( dataPoints.length() == 0 ) return;
//printf("|%s|\n", (databaseIP + "write?db=" + databaseName).c_str());
curl_easy_setopt(curl, CURLOPT_URL, (databaseIP + "write?db=" + databaseName).c_str());
curl_easy_setopt(curl, CURLOPT_POST, 1L);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_HEADER, 0);
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, static_cast<long>(dataPoints.length()));
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, dataPoints.c_str());
Execute();
}
void InfluxDB::Execute(){
DebugPrint("%s", "InfluxDB");
// printf(" InfluxDB::%s \n", __func__);
try{
respond = curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &respondCode);
//printf("==== respond %d (OK = %d)\n", respond, CURLE_OK);
if( respond != CURLE_OK ) printf("############# InfluxDB::Execute fail | %ld\n", respondCode);
} catch (std::exception& e){ // in case of unexpected error
printf("%s\n", e.what());
respond = CURLE_SEND_ERROR;
}
}
size_t InfluxDB::WriteCallBack(char *contents, size_t size, size_t nmemb, void *userp){
DebugPrint("%s", "InfluxDB");
// printf(" InfluxDB::%s \n", __func__);
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}

View File

@ -3,9 +3,6 @@
#include <QThread>
#include <QMutex>
#include <QWaitCondition>
#include <QMessageBox>
#include <QCoreApplication>
#include "macro.h"
#include "ClassDigitizer.h"
@ -27,23 +24,11 @@ public:
void Stop() { this->stop = true;}
void SetSaveData(bool onOff) {this->isSaveData = onOff;}
void SetScopeMode(bool onOff) {this->isScope = onOff;}
void SetReadCountZero() {readCount = 0;}
unsigned long GetReadCount() const {return readCount;}
void run(){
stop = false;
readCount = 0;
clock_gettime(CLOCK_REALTIME, &t0);
// ta = t0;
t1 = t0;
digiMTX[ID].lock();
digi->ReadACQStatus();
digiMTX[ID].unlock();
printf("ReadDataThread for digi-%d running.\n", digi->GetSerialNumber());
ta = t0;
// clock_gettime(CLOCK_REALTIME, &t1);
stop = false;
do{
if( stop) break;
@ -54,49 +39,40 @@ public:
readCount ++;
if( stop) break;
if( ret == CAEN_DGTZ_Success && !stop){
digiMTX[ID].lock();
digi->GetData()->DecodeBuffer(!isScope, 0);
if( isSaveData ) digi->GetData()->SaveData();
digiMTX[ID].unlock();
// clock_gettime(CLOCK_REALTIME, &t2);
// if( t2.tv_sec - t1.tv_sec > 2 ) {
// printf("----Digi-%d read %ld / sec.\n", ID, readCount / 3);
// readCount = 0;
// t1 = t2;
// }
}else{
printf("ReadDataThread::%s------------ ret : %d \n", __func__, ret);
digiMTX[ID].lock();
digi->StopACQ();
if( ret == CAEN_DGTZ_OutOfMemory ){
digi->WriteRegister(DPP::SoftwareClear_W, 1);
digi->GetData()->ClearData();
}
digiMTX[ID].unlock();
emit sendMsg("Digi-" + QString::number(digi->GetSerialNumber()) + " ACQ off.");
stop = true;
break;
}
clock_gettime(CLOCK_REALTIME, &t2);
if( t2.tv_sec - t1.tv_sec > 1 ){
digiMTX[ID].lock();
digi->ReadACQStatus();
digiMTX[ID].unlock();
t2 = t1;
// QCoreApplication::processEvents();
if( isSaveData && !stop ) {
clock_gettime(CLOCK_REALTIME, &tb);
if( tb.tv_sec - ta.tv_sec > 2 ) {
digiMTX[ID].lock();
emit sendMsg("FileSize ("+ QString::number(digi->GetSerialNumber()) +"): " + QString::number(digi->GetData()->GetTotalFileSize()/1024./1024., 'f', 4) + " MB [" + QString::number(tb.tv_sec-t0.tv_sec) + " sec]");
//digi->GetData()->PrintStat();
digiMTX[ID].unlock();
ta = tb;
}
}
// if( isSaveData && !stop ) {
// clock_gettime(CLOCK_REALTIME, &tb);
// if( tb.tv_sec - ta.tv_sec > 2 ) {
// digiMTX[ID].lock();
// emit sendMsg("FileSize ("+ QString::number(digi->GetSerialNumber()) +"): " + QString::number(digi->GetData()->GetTotalFileSize()/1024./1024., 'f', 4) + " MB [" + QString::number(tb.tv_sec-t0.tv_sec) + " sec]");
// //emit sendMsg("FileSize ("+ QString::number(digi->GetSerialNumber()) +"): " + QString::number(digi->GetData()->GetTotalFileSize()/1024./1024., 'f', 4) + " MB [" + QString::number(tb.tv_sec-t0.tv_sec) + " sec] (" + QString::number(readCount) + ")");
// digiMTX[ID].unlock();
// // readCount = 0;
// ta = tb;
// }
// }
}while(!stop);
printf("ReadDataThread for digi-%d stopped.\n", digi->GetSerialNumber());
printf("ReadDataThread stopped.\n");
}
signals:
void sendMsg(const QString &msg);
@ -107,7 +83,7 @@ private:
timespec ta, tb, t1, t2, t0;
bool isSaveData;
bool isScope;
unsigned long readCount;
unsigned long readCount;
};
//^#======================================================= Timing Thread
@ -115,14 +91,12 @@ class TimingThread : public QThread {
Q_OBJECT
public:
TimingThread(QObject * parent = 0 ) : QThread(parent){
waitTime = 20; // multiple of 100 mili sec
waitTime = 20; // 10 x 100 milisec
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.;}
void DoOnce() {emit timeUp();};
void run(){
unsigned int count = 0;
stop = false;

View File

@ -16,7 +16,6 @@
#include <QLineSeries>
#include <QAreaSeries>
#include <QValueAxis>
#include <QMenu>
//^====================================================
class RSpinBox : public QDoubleSpinBox{
@ -61,14 +60,14 @@ class RComboBox : public QComboBox{
};
//^====================================================
class RChart : public QChart{
class Trace : public QChart{
public:
explicit RChart(QGraphicsItem *parent = nullptr, Qt::WindowFlags wFlags = {})
explicit Trace(QGraphicsItem *parent = nullptr, Qt::WindowFlags wFlags = {})
: QChart(QChart::ChartTypeCartesian, parent, wFlags){
grabGesture(Qt::PanGesture);
grabGesture(Qt::PinchGesture);
}
~RChart(){}
~Trace(){}
protected:
bool sceneEvent(QEvent *event){
@ -95,9 +94,9 @@ private:
};
//^====================================================
class RChartView : public QChartView{
class TraceView : public QChartView{
public:
RChartView(QChart * chart, QWidget * parent = nullptr): QChartView(chart, parent){
TraceView(QChart * chart, QWidget * parent = nullptr): QChartView(chart, parent){
m_isTouching = false;
this->setRubberBand(QChartView::RectangleRubberBand);
@ -109,6 +108,17 @@ public:
setRenderHints(QPainter::Antialiasing);
vRangeMin = -(0x1FFF);
vRangeMax = 0x1FFF;
}
void SetHRange(int min, int max) {
this->hRangeMin = min;
this->hRangeMax = max;
}
void SetVRange(int min, int max) {
this->vRangeMin = min;
this->vRangeMax = max;
}
protected:
bool viewportEvent(QEvent *event) override{
@ -121,26 +131,7 @@ protected:
void mousePressEvent(QMouseEvent *event) override{
if (m_isTouching) return;
QChartView::mousePressEvent(event);
if (event->button() == Qt::RightButton) {
QMenu *menu = new QMenu(this);
menu->setAttribute(Qt::WA_DeleteOnClose);
QAction * a1 = menu->addAction("UnZoom");
QAction *selectedAction = menu->exec(event->globalPosition().toPoint());
if( selectedAction == a1 ) {
chart()->zoomReset();
// chart()->axes(Qt::Vertical).first()->setRange(-(0x3FFF), 0x3FFF);
}
}
}
void wheelEvent(QWheelEvent * event) override{
qreal zoomFactor = event->angleDelta().y() > 0 ? 0.9 : 1.1;
chart()->zoom(zoomFactor);
}
void mouseMoveEvent(QMouseEvent *event) override{
QPointF chartPoint = this->chart()->mapToValue(event->pos());
QString coordinateText = QString("x: %1, y: %2").arg(QString::number(chartPoint.x(), 'f', 0)).arg(QString::number(chartPoint.y(), 'f', 0));
@ -168,8 +159,9 @@ protected:
case Qt::Key_Up: chart()->scroll(0, 10); break;
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(-(0x1FFF), 0x1FFF);
chart()->axes(Qt::Vertical).first()->setRange(vRangeMin, vRangeMax);
//chart()->axes(Qt::Horizontal).first()->setRange(hRangeMin, hRangeMax);
break;
default: QGraphicsView::keyPressEvent(event); break;
}
@ -177,7 +169,116 @@ protected:
private:
bool m_isTouching;
int hRangeMin;
int hRangeMax;
int vRangeMin;
int vRangeMax;
QLabel * m_coordinateLabel;
};
//^====================================================
class Histogram {
public:
Histogram(QString title, double xMin, double xMax, int nBin){
plot = new Trace();
dataSeries = new QLineSeries();
Rebin(xMin, xMax, nBin);
maxBin = -1;
maxBinValue = 0;
//dataSeries->setPen(QPen(Qt::blue, 1));
areaSeries = new QAreaSeries(dataSeries);
areaSeries->setName(title);
areaSeries->setBrush(Qt::blue);
plot->addSeries(areaSeries);
plot->setAnimationDuration(1); // msec
plot->setAnimationOptions(QChart::NoAnimation);
plot->createDefaultAxes();
QValueAxis * xaxis = qobject_cast<QValueAxis*> (plot->axes(Qt::Horizontal).first());
xaxis->setRange(xMin, xMax);
xaxis->setTickCount( nBin + 1 > 11 ? 11 : nBin + 1);
//xaxis->setLabelFormat("%.1f");
//xaxis->setTitleText("Time [ns]");
QValueAxis * yaxis = qobject_cast<QValueAxis*> (plot->axes(Qt::Vertical).first());
yaxis->setRange(0, 10);
}
~Histogram(){
delete areaSeries;
delete dataSeries;
delete plot;
}
Trace * GetTrace() { return plot;}
void Clear(){
for( int i = 0; i <= nBin; i++) {
dataSeries->replace(2*i, xMin + i * dX, 0);
dataSeries->replace(2*i+1, xMin + i * dX, 0);
}
}
void SetColor(Qt::GlobalColor color){ areaSeries->setBrush(color);}
void Rebin(double xMin, double xMax, int nBin){
dataSeries->clear();
this->xMin = xMin;
this->xMax = xMax;
this->nBin = nBin;
dX = (xMax-xMin)/nBin;
for( int i = 0; i <= nBin; i++) {
dataSeries->append(xMin + i * dX, 0 );
dataSeries->append(xMin + i * dX, 0 );
}
}
void Fill(double value){
double bin = (value - xMin)/dX;
if( bin < 0 || bin >= nBin ) return;
int index1 = 2*qFloor(bin) + 1;
int index2 = index1 + 1;
QPointF point1 = dataSeries->at(index1);
dataSeries->replace(index1, point1.x(), point1.y() + 1);
QPointF point2 = dataSeries->at(index2);
dataSeries->replace(index2, point2.x(), point2.y() + 1);
if( point2.y() + 1 > maxBinValue ){
maxBinValue = point2.y() + 1;
maxBin = index2/2;
}
QValueAxis * yaxis = qobject_cast<QValueAxis*> (plot->axes(Qt::Vertical).first());
yaxis->setRange(0, maxBinValue < 10 ? 10 : ((double)maxBinValue) * 1.2 );
//yaxis->setTickInterval(1);
//yaxis->setTickCount(10);
//yaxis->setLabelFormat("%.0f");
}
private:
Trace * plot;
QLineSeries * dataSeries;
QAreaSeries * areaSeries;
double dX, xMin, xMax;
int nBin;
int maxBin;
int maxBinValue;
};
//^====================================================
#endif

59
DataReaderScript.cpp Normal file
View File

@ -0,0 +1,59 @@
#include "ClassData.h"
void DataReaderScript(){
Data * data = new Data();
data->DPPType = V1730_DPP_PSD_CODE;
std::string fileName = "data/temp_006_089_PSD_000.fsu";
FILE * haha = fopen(fileName.c_str(), "r");
fseek(haha, 0L, SEEK_END);
const long inFileSize = ftell(haha);
printf("%s | file size : %ld Byte = %.2f MB\n", fileName.c_str() , inFileSize, inFileSize/1024./1024.);
fseek(haha, 0, SEEK_SET);
char * buffer = nullptr;
int countBdAgg = 0;
do{
long fPos1 = ftell(haha);
unsigned int word[1]; /// 4 bytes
size_t dump = fread(word, 4, 1, haha);
fseek(haha, -4, SEEK_CUR);
short header = ((word[0] >> 28 ) & 0xF);
if( header != 0xA ) break;
unsigned int aggSize = (word[0] & 0x0FFFFFFF) * 4; ///byte
buffer = new char[aggSize];
dump = fread(buffer, aggSize, 1, haha);
long fPos2 = ftell(haha);
printf("Board Agg. has %d word = %d bytes | %ld - %ld\n", aggSize/4, aggSize, fPos1, fPos2);
countBdAgg ++;
printf("==================== %d Agg\n", countBdAgg);
data->DecodeBuffer(buffer, aggSize, false, 0); // data own the buffer
data->ClearBuffer(); // this will clear the buffer.
if( !data->IsNotRollOverFakeAgg ) continue;
//if( countBdAgg % 100 == 0)
data->PrintStat();
//data->ClearData();
if( countBdAgg > 1 ) break;
}while(!feof(haha) && ftell(haha) < inFileSize);
data->PrintAllData();
fclose(haha);
delete data;
}

File diff suppressed because it is too large Load Diff

View File

@ -21,20 +21,13 @@ public:
DigiSettingsPanel(Digitizer ** digi, unsigned int nDigi, QString rawDataPath, QMainWindow * parent = nullptr);
~DigiSettingsPanel();
unsigned short GetTabID() const {return ID;}
public slots:
void UpdatePanelFromMemory();
void ReadSettingsFromBoard();
void UpdateACQStatus(uint32_t status);
void UpdateReadOutStatus(uint32_t status);
void UpdateBoardAndChannelsStatus(); // directly read from register
void SaveSetting(int opt);
void LoadSetting();
void EnableButtons(bool enable);
signals:
void SendLogMsg(const QString &msg);
void UpdateOtherPanels();
@ -45,38 +38,34 @@ private:
void SetUpCheckBox(QCheckBox * &chkBox, QString label, QGridLayout *gLayout, int row, int col, Reg para, std::pair<unsigned short, unsigned short> bit, int ch = -1, int colSpan = 1);
void SetUpComboBoxBit(RComboBox * &cb, QString label, QGridLayout *gLayout, int row, int col, std::vector<std::pair<std::string, unsigned int>> items, Reg para, std::pair<unsigned short, unsigned short> bit, int colspan = 1, int ch = -1);
void SetUpComboBox(RComboBox * &cb, QString label, QGridLayout *gLayout, int row, int col, Reg para, int ch = -1);
void SetUpSpinBox(RSpinBox * &sb, QString label, QGridLayout *gLayout, int row, int col, Reg para, int ch = -1, bool isBoard = false);
void SetUpSpinBox(RSpinBox * &sb, QString label, QGridLayout *gLayout, int row, int col, Reg para, int ch = -1);
void CleanUpGroupBox(QGroupBox * & gBox);
void SetUpChannelMask(unsigned int digiID);
void SetUpChannelMask();
void SetUpACQReadOutTab();
void SetUpGlobalTriggerMaskAndFrontPanelMask(QGridLayout * & gLayout);
void SetUpInquiryCopyTab();
void SetUpBoard_PHA();
void SetUpChannel_PHA();
void SetUpPHABoard();
void SetUpPHAChannel();
void SetUpBoard_PSD();
void SetUpChannel_PSD();
void SetUpBoard_QDC();
void SetUpChannel_QDC();
void SetUpPSDBoard();
void SetUpPSDChannel();
void UpdateSpinBox(RSpinBox * &sb, Reg para, int ch);
void UpdateComboBox(RComboBox * &cb, Reg para, int ch);
void UpdateComboBoxBit(RComboBox * &cb, uint32_t fullBit, std::pair<unsigned short, unsigned short> bit);
void SyncSpinBox(RSpinBox *(&spb)[][MaxRegChannel+1]);
void SyncComboBox(RComboBox *(&cb)[][MaxRegChannel+1]);
void SyncCheckBox(QCheckBox *(&chk)[][MaxRegChannel+1]);
void SyncSpinBox(RSpinBox *(&spb)[][MaxNChannels+1]);
void SyncComboBox(RComboBox *(&cb)[][MaxNChannels+1]);
void SyncCheckBox(QCheckBox *(&chk)[][MaxNChannels+1]);
void UpdateBoardAndChannelsStatus(); // ReadRegister
void SyncAllChannelsTab_PHA();
void UpdateSettings_PHA();
void UpdatePHASetting();
void SyncAllChannelsTab_PSD();
void UpdateSettings_PSD();
void SyncAllChannelsTab_QDC();
void UpdateSettings_QDC();
void UpdatePSDSetting();
void CheckRadioAndCheckedButtons();
@ -88,8 +77,8 @@ private:
RComboBox * cbFromBoard;
RComboBox * cbToBoard;
QRadioButton * rbCh[MaxRegChannel]; // Copy from ch
QCheckBox * chkCh[MaxRegChannel]; // Copy to Ch
QRadioButton * rbCh[MaxNChannels]; // Copy from ch
QCheckBox * chkCh[MaxNChannels]; // Copy to Ch
QPushButton * bnCopyBoard;
QPushButton * bnCopyChannel;
@ -103,20 +92,15 @@ private:
QLineEdit * leSaveFilePath[MaxNDigitizer];
QWidget * buttonsWidget[MaxNDigitizer];
QPushButton * bnRefreshSetting; // read setting from board
QPushButton * bnProgramPreDefined;
QPushButton * bnClearBuffer;
// QPushButton * bnSendSoftwareTriggerSignal;
QPushButton * bnSetNoTrace;
QPushButton * bhAutoSetEventPulling;
//QPushButton * bnSendSoftwareClockSyncSignal;
QPushButton * bnSendSoftwareTriggerSignal;
QPushButton * bnSendSoftwareClockSyncSignal;
QPushButton * bnSaveSettings;
QPushButton * bnLoadSettings;
//QPushButton * bnSaveSettingsToText;
QCheckBox * chkCoupledSettingFile;
QPushButton * bnSaveSettingsToText;
/// ============================= Board Configure
QGridLayout * bdCfgLayout[MaxNDigitizer];
@ -125,9 +109,6 @@ private:
QGridLayout * bdTriggerLayout[MaxNDigitizer];
QGridLayout * bdLVDSLayout[MaxNDigitizer];
// RComboBox * cbSWDecimation[MaxNDigitizer]; // software decimation
RSpinBox * sbSWDecimation[MaxNDigitizer];
QCheckBox * chkAutoDataFlush[MaxNDigitizer];
QCheckBox * chkDecimateTrace[MaxNDigitizer];
QCheckBox * chkTrigPropagation[MaxNDigitizer];
@ -140,8 +121,7 @@ private:
RComboBox * cbDigiProbe1[MaxNDigitizer];
RComboBox * cbDigiProbe2[MaxNDigitizer];
QPushButton * bnChEnableMask[MaxNDigitizer][MaxRegChannel];
QCheckBox * cbDigiEnable[MaxNDigitizer];
QPushButton * bnChEnableMask[MaxNDigitizer][MaxNChannels];
RComboBox * cbAggOrg[MaxNDigitizer];
RSpinBox * sbAggNum[MaxNDigitizer];
QCheckBox * chkEnableExternalTrigger[MaxNDigitizer];
@ -169,11 +149,11 @@ private:
QCheckBox * chkEnableExtendedBlockTransfer[MaxNDigitizer];
/// ============================= trigger validation mask
RComboBox * cbMaskLogic[MaxNDigitizer][MaxRegChannel/2];
RSpinBox * sbMaskMajorLevel[MaxNDigitizer][MaxRegChannel/2];
QCheckBox * chkMaskExtTrigger[MaxNDigitizer][MaxRegChannel/2];
QCheckBox * chkMaskSWTrigger[MaxNDigitizer][MaxRegChannel/2];
QPushButton * bnTriggerMask[MaxNDigitizer][MaxRegChannel/2][MaxRegChannel/2];
RComboBox * cbMaskLogic[MaxNDigitizer][MaxNChannels/2];
RSpinBox * sbMaskMajorLevel[MaxNDigitizer][MaxNChannels/2];
QCheckBox * chkMaskExtTrigger[MaxNDigitizer][MaxNChannels/2];
QCheckBox * chkMaskSWTrigger[MaxNDigitizer][MaxNChannels/2];
QPushButton * bnTriggerMask[MaxNDigitizer][MaxNChannels/2][MaxNChannels/2];
/// ============================= board Status
QPushButton * bnACQStatus[MaxNDigitizer][9];
@ -184,12 +164,12 @@ private:
QLineEdit * leReadOutStatus[MaxNDigitizer];
/// ============================= Mask Configure
QPushButton * bnGlobalTriggerMask[MaxNDigitizer][MaxRegChannel/2];
QPushButton * bnGlobalTriggerMask[MaxNDigitizer][MaxNChannels/2];
RSpinBox * sbGlbMajCoinWin[MaxNDigitizer];
RSpinBox * sbGlbMajLvl[MaxNDigitizer];
RComboBox * cbGlbUseOtherTriggers[MaxNDigitizer]; // combine bit 30, 31
QPushButton * bnTRGOUTMask[MaxNDigitizer][MaxRegChannel/2];
QPushButton * bnTRGOUTMask[MaxNDigitizer][MaxNChannels/2];
RSpinBox * sbTRGOUTMajLvl[MaxNDigitizer];
RComboBox * cbTRGOUTLogic[MaxNDigitizer];
RComboBox * cbTRGOUTUseOtherTriggers[MaxNDigitizer]; // combine bit 30, 31
@ -198,113 +178,93 @@ private:
QTabWidget * chTab;
RComboBox * chSelection[MaxNDigitizer];
QPushButton * bnProgramChannel[MaxNDigitizer];
//----------- common for PHA and PSD
RSpinBox * sbRecordLength[MaxNDigitizer][MaxRegChannel + 1];
RComboBox * cbDynamicRange[MaxNDigitizer][MaxRegChannel + 1];
RSpinBox * sbPreTrigger[MaxNDigitizer][MaxRegChannel + 1];
RSpinBox * sbThreshold[MaxNDigitizer][MaxRegChannel + 1];
RSpinBox * sbDCOffset[MaxNDigitizer][MaxRegChannel + 1];
RComboBox * cbPolarity[MaxNDigitizer][MaxRegChannel + 1];
RSpinBox * sbShapedTrigWidth[MaxNDigitizer][MaxRegChannel + 1];
RSpinBox * sbTriggerHoldOff[MaxNDigitizer][MaxRegChannel + 1];
RComboBox * cbTrigMode[MaxNDigitizer][MaxRegChannel + 1];
RComboBox * cbBaseLineAvg[MaxNDigitizer][MaxRegChannel + 1];
RSpinBox * sbNumEventAgg[MaxNDigitizer][MaxRegChannel + 1];
RSpinBox * sbVetoWidth[MaxNDigitizer][MaxRegChannel + 1];
RComboBox * cbVetoStep[MaxNDigitizer][MaxRegChannel + 1];
RSpinBox * sbRecordLength[MaxNDigitizer][MaxNChannels + 1];
RComboBox * cbDynamicRange[MaxNDigitizer][MaxNChannels + 1];
RSpinBox * sbPreTrigger[MaxNDigitizer][MaxNChannels + 1];
RSpinBox * sbThreshold[MaxNDigitizer][MaxNChannels + 1];
RSpinBox * sbDCOffset[MaxNDigitizer][MaxNChannels + 1];
RComboBox * cbPolarity[MaxNDigitizer][MaxNChannels + 1];
RSpinBox * sbShapedTrigWidth[MaxNDigitizer][MaxNChannels + 1];
RSpinBox * sbTriggerHoldOff[MaxNDigitizer][MaxNChannels + 1];
RComboBox * cbTrigMode[MaxNDigitizer][MaxNChannels + 1];
RComboBox * cbBaseLineAvg[MaxNDigitizer][MaxNChannels + 1];
RSpinBox * sbNumEventAgg[MaxNDigitizer][MaxNChannels + 1];
RSpinBox * sbVetoWidth[MaxNDigitizer][MaxNChannels + 1];
RComboBox * cbVetoStep[MaxNDigitizer][MaxNChannels + 1];
RComboBox * cbLocalShapedTrigger[MaxNDigitizer][MaxRegChannel + 1];
RComboBox * cbLocalTriggerValid[MaxNDigitizer][MaxRegChannel + 1];
RComboBox * cbExtra2Option[MaxNDigitizer][MaxRegChannel + 1];
RComboBox * cbVetoSource[MaxNDigitizer][MaxRegChannel + 1];
QCheckBox * chkDisableSelfTrigger[MaxNDigitizer][MaxRegChannel + 1];
RComboBox * cbTrigCount[MaxNDigitizer][MaxRegChannel + 1];
RComboBox * cbTRGOUTChannelProbe[MaxNDigitizer][MaxRegChannel + 1];
RComboBox * cbLocalShapedTrigger[MaxNDigitizer][MaxNChannels + 1];
RComboBox * cbLocalTriggerValid[MaxNDigitizer][MaxNChannels + 1];
RComboBox * cbExtra2Option[MaxNDigitizer][MaxNChannels + 1];
RComboBox * cbVetoSource[MaxNDigitizer][MaxNChannels + 1];
QCheckBox * chkDisableSelfTrigger[MaxNDigitizer][MaxNChannels + 1];
RComboBox * cbTrigCount[MaxNDigitizer][MaxNChannels + 1];
//---------- PHA
RComboBox * cbRCCR2Smoothing[MaxNDigitizer][MaxRegChannel + 1];
RSpinBox * sbInputRiseTime[MaxNDigitizer][MaxRegChannel + 1];
RSpinBox * sbRiseTimeValidWin[MaxNDigitizer][MaxRegChannel + 1];
RComboBox * cbRCCR2Smoothing[MaxNDigitizer][MaxNChannels + 1];
RSpinBox * sbInputRiseTime[MaxNDigitizer][MaxNChannels + 1];
RSpinBox * sbRiseTimeValidWin[MaxNDigitizer][MaxNChannels + 1];
RSpinBox * sbTrapRiseTime[MaxNDigitizer][MaxRegChannel + 1];
RSpinBox * sbTrapFlatTop[MaxNDigitizer][MaxRegChannel + 1];
RSpinBox * sbDecay[MaxNDigitizer][MaxRegChannel + 1];
RSpinBox * sbTrapScaling[MaxNDigitizer][MaxRegChannel + 1];
RSpinBox * sbPeaking[MaxNDigitizer][MaxRegChannel + 1];
RSpinBox * sbPeakingHoldOff[MaxNDigitizer][MaxRegChannel + 1];
RComboBox * cbPeakAvg[MaxNDigitizer][MaxRegChannel + 1];
QCheckBox * chkActiveBaseline[MaxNDigitizer][MaxRegChannel + 1];
QCheckBox * chkBaselineRestore[MaxNDigitizer][MaxRegChannel + 1];
// RSpinBox * sbFineGain[MaxNDigitizer][MaxRegChannel + 1];
RSpinBox * sbTrapRiseTime[MaxNDigitizer][MaxNChannels + 1];
RSpinBox * sbTrapFlatTop[MaxNDigitizer][MaxNChannels + 1];
RSpinBox * sbDecay[MaxNDigitizer][MaxNChannels + 1];
RSpinBox * sbTrapScaling[MaxNDigitizer][MaxNChannels + 1];
RSpinBox * sbPeaking[MaxNDigitizer][MaxNChannels + 1];
RSpinBox * sbPeakingHoldOff[MaxNDigitizer][MaxNChannels + 1];
RComboBox * cbPeakAvg[MaxNDigitizer][MaxNChannels + 1];
QCheckBox * chkActiveBaseline[MaxNDigitizer][MaxNChannels + 1];
QCheckBox * chkBaselineRestore[MaxNDigitizer][MaxNChannels + 1];
RSpinBox * sbFineGain[MaxNDigitizer][MaxNChannels + 1];
QCheckBox * chkEnableRollOver[MaxNDigitizer][MaxRegChannel + 1];
QCheckBox * chkEnablePileUp[MaxNDigitizer][MaxRegChannel + 1];
QCheckBox * chkTagCorrelation[MaxNDigitizer][MaxRegChannel + 1];
RComboBox * cbDecimateTrace[MaxNDigitizer][MaxRegChannel + 1];
RComboBox * cbDecimateGain[MaxNDigitizer][MaxRegChannel + 1];
QCheckBox * chkEnableRollOver[MaxNDigitizer][MaxNChannels + 1];
QCheckBox * chkEnablePileUp[MaxNDigitizer][MaxNChannels + 1];
QCheckBox * chkTagCorrelation[MaxNDigitizer][MaxNChannels + 1];
RComboBox * cbDecimateTrace[MaxNDigitizer][MaxNChannels + 1];
RComboBox * cbDecimateGain[MaxNDigitizer][MaxNChannels + 1];
//---------------- PSD
RComboBox * cbChargeSensitivity[MaxNDigitizer][MaxRegChannel + 1];
QCheckBox * chkChargePedestal[MaxNDigitizer][MaxRegChannel + 1];
RComboBox * cbTriggerOpt[MaxNDigitizer][MaxRegChannel + 1];
RComboBox * cbDiscriMode[MaxNDigitizer][MaxRegChannel + 1];
QCheckBox * chkPileUpInGate[MaxNDigitizer][MaxRegChannel + 1];
QCheckBox * chkTestPule[MaxNDigitizer][MaxRegChannel + 1];
RComboBox * cbTestPulseRate[MaxNDigitizer][MaxRegChannel + 1];
QCheckBox * chkBaseLineCal[MaxNDigitizer][MaxRegChannel + 1];
QCheckBox * chkDiscardQLong[MaxNDigitizer][MaxRegChannel + 1];
QCheckBox * chkRejPileUp[MaxNDigitizer][MaxRegChannel + 1];
QCheckBox * chkCutBelow[MaxNDigitizer][MaxRegChannel + 1];
QCheckBox * chkCutAbove[MaxNDigitizer][MaxRegChannel + 1];
QCheckBox * chkRejOverRange[MaxNDigitizer][MaxRegChannel + 1];
QCheckBox * chkDisableTriggerHysteresis[MaxNDigitizer][MaxRegChannel + 1];
QCheckBox * chkDisableOppositePulse[MaxNDigitizer][MaxRegChannel + 1];
RComboBox * cbChargeSensitivity[MaxNDigitizer][MaxNChannels + 1];
QCheckBox * chkChargePedestal[MaxNDigitizer][MaxNChannels + 1];
RComboBox * cbTriggerOpt[MaxNDigitizer][MaxNChannels + 1];
RComboBox * cbDiscriMode[MaxNDigitizer][MaxNChannels + 1];
QCheckBox * chkPileUpInGate[MaxNDigitizer][MaxNChannels + 1];
QCheckBox * chkTestPule[MaxNDigitizer][MaxNChannels + 1];
RComboBox * cbTestPulseRate[MaxNDigitizer][MaxNChannels + 1];
QCheckBox * chkBaseLineCal[MaxNDigitizer][MaxNChannels + 1];
QCheckBox * chkDiscardQLong[MaxNDigitizer][MaxNChannels + 1];
QCheckBox * chkRejPileUp[MaxNDigitizer][MaxNChannels + 1];
QCheckBox * chkCutBelow[MaxNDigitizer][MaxNChannels + 1];
QCheckBox * chkCutAbove[MaxNDigitizer][MaxNChannels + 1];
QCheckBox * chkRejOverRange[MaxNDigitizer][MaxNChannels + 1];
QCheckBox * chkDisableTriggerHysteresis[MaxNDigitizer][MaxNChannels + 1];
QCheckBox * chkDisableOppositePulse[MaxNDigitizer][MaxNChannels + 1];
RSpinBox * sbChargeZeroSupZero[MaxNDigitizer][MaxRegChannel + 1];
RSpinBox * sbShortGate[MaxNDigitizer][MaxRegChannel + 1];
RSpinBox * sbLongGate[MaxNDigitizer][MaxRegChannel + 1];
RSpinBox * sbGateOffset[MaxNDigitizer][MaxRegChannel + 1];
RSpinBox * sbFixedBaseline[MaxNDigitizer][MaxRegChannel + 1];
RSpinBox * sbTriggerLatency[MaxNDigitizer][MaxRegChannel + 1];
RSpinBox * sbPSDCutThreshold[MaxNDigitizer][MaxRegChannel + 1];
RSpinBox * sbPURGAPThreshold[MaxNDigitizer][MaxRegChannel + 1];
RSpinBox * sbChargeZeroSupZero[MaxNDigitizer][MaxNChannels + 1];
RSpinBox * sbShortGate[MaxNDigitizer][MaxNChannels + 1];
RSpinBox * sbLongGate[MaxNDigitizer][MaxNChannels + 1];
RSpinBox * sbGateOffset[MaxNDigitizer][MaxNChannels + 1];
RSpinBox * sbFixedBaseline[MaxNDigitizer][MaxNChannels + 1];
RSpinBox * sbTriggerLatency[MaxNDigitizer][MaxNChannels + 1];
RSpinBox * sbPSDCutThreshold[MaxNDigitizer][MaxNChannels + 1];
RSpinBox * sbPURGAPThreshold[MaxNDigitizer][MaxNChannels + 1];
RSpinBox * sbCFDDely[MaxNDigitizer][MaxRegChannel + 1];
RComboBox * cbCFDFraction[MaxNDigitizer][MaxRegChannel + 1];
RComboBox * cbCFDInterpolation[MaxNDigitizer][MaxRegChannel + 1];
RSpinBox * sbCFDDely[MaxNDigitizer][MaxNChannels + 1];
RComboBox * cbCFDFraction[MaxNDigitizer][MaxNChannels + 1];
RComboBox * cbCFDInterpolation[MaxNDigitizer][MaxNChannels + 1];
RComboBox * cbSmoothedChargeIntegration[MaxNDigitizer][MaxRegChannel + 1];
QCheckBox * chkMarkSaturation[MaxNDigitizer][MaxRegChannel + 1];
RComboBox * cbAdditionLocalTrigValid[MaxNDigitizer][MaxRegChannel + 1];
RComboBox * cbSmoothedChargeIntegration[MaxNDigitizer][MaxNChannels + 1];
QCheckBox * chkMarkSaturation[MaxNDigitizer][MaxNChannels + 1];
RComboBox * cbAdditionLocalTrigValid[MaxNDigitizer][MaxNChannels + 1];
RComboBox * cbVetoMode[MaxNDigitizer][MaxRegChannel + 1];
QCheckBox * chkResetTimestampByTRGIN[MaxNDigitizer][MaxRegChannel + 1];
RComboBox * cbVetoMode[MaxNDigitizer][MaxNChannels + 1];
QCheckBox * chkResetTimestampByTRGIN[MaxNDigitizer][MaxNChannels + 1];
//------------------- QDC
RComboBox * cbExtTriggerMode[MaxNDigitizer];
RSpinBox * sbEventPreAgg_QDC[MaxNDigitizer];
//...... reuse varaible
//Gate Width -> sbShortGate
//Gate offset -> sbGateOffset
//PreTrigger -> sbPreTrigger
//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];
QPushButton * pbSubChMask[MaxNDigitizer][MaxRegChannel+1][8];
RSpinBox * sbSubChOffset[MaxNDigitizer][MaxRegChannel + 1][8];
RSpinBox * sbSubChThreshold[MaxNDigitizer][MaxRegChannel + 1][8];
QLabel * lbSubCh[MaxNDigitizer][8];
QLabel * lbSubCh2[MaxNDigitizer][8];
//---------------- channel status
QPushButton * bnChStatus[MaxNDigitizer][MaxRegChannel][3];
QLineEdit * leADCTemp[MaxNDigitizer][MaxRegChannel];
QPushButton * bnChStatus[MaxNDigitizer][MaxNChannels][3];
QLineEdit * leADCTemp[MaxNDigitizer][MaxNChannels];
};

446
EventBuilder.cpp Normal file
View File

@ -0,0 +1,446 @@
#include "ClassData.h"
#include "TROOT.h"
#include "TSystem.h"
#include "TClonesArray.h"
#include "TGraph.h"
#include "TFile.h"
#include "TTree.h"
#define MAX_MULTI 100
#define NTimeWinForBuffer 3
TFile * outRootFile = NULL;
TTree * tree = NULL;
unsigned long long evID = 0;
unsigned short multi = 0;
unsigned short bd[MAX_MULTI] = {0}; /// boardID
unsigned short ch[MAX_MULTI] = {0}; /// chID
unsigned short e[MAX_MULTI] = {0}; /// 15 bit
unsigned long long e_t[MAX_MULTI] = {0}; /// timestamp 47 bit
unsigned short e_f[MAX_MULTI] = {0}; /// fine time 10 bit
class Trace{
public:
Trace() {trace.clear(); }
~Trace();
void Clear() { trace.clear(); };
Trace operator = (std::vector<unsigned short> v){
Trace tt;
for( int i = 0 ; i < (int) v.size() ; i++){
trace.push_back(v[i]);
}
return tt;
}
std::vector<unsigned short> trace;
};
/// using TClonesArray to hold the trace in TGraph
TClonesArray * arrayTrace = NULL;
unsigned short traceLength[MAX_MULTI] = {0};
TGraph * trace = NULL;
template<typename T> void swap(T * a, T *b );
int partition(int arr[], int kaka[], TString file[], int start, int end);
void quickSort(int arr[], int kaka[], TString file[], int start, int end);
void EventBuilder(Data * data, const unsigned int timeWin, bool traceOn = false, bool isLastData = false, unsigned int verbose = 0);
//*#############################################################
//*#############################################################
int main(int argc, char **argv) {
printf("=====================================\n");
printf("=== *.fsu Events Builder ===\n");
printf("=====================================\n");
if (argc <= 3) {
printf("Incorrect number of arguments:\n");
printf("%s [timeWindow] [traceOn/Off] [verbose] [inFile1] [inFile2] .... \n", argv[0]);
printf(" timeWindow : number of tick, 1 tick. default = 100 \n");
printf(" traceOn/Off : is traces stored \n");
printf(" verbose : > 0 for debug \n");
printf(" Output file name is contructed from inFile1 \n");
return 1;
}
/// File format must be YYY...Y_runXXX_AAA_BBB_CCC.fsu
/// YYY...Y = prefix
/// XXX = runID, 3 digits
/// AAA = board Serial Number, 3 digits
/// BBB = DPPtype, 3 digits
/// CCC = over size index, 3 digits
///============= read input
unsigned int timeWindow = atoi(argv[1]);
bool traceOn = atoi(argv[2]);
unsigned int debug = atoi(argv[3]);
int nFile = argc - 4;
TString inFileName[nFile];
for( int i = 0 ; i < nFile ; i++){
inFileName[i] = argv[i+4];
}
/// Form outFileName;
TString outFileName = inFileName[0];
int pos = outFileName.Index("_");
pos = outFileName.Index("_", pos+1);
outFileName.Remove(pos);
outFileName += ".root";
printf("-------> Out file name : %s \n", outFileName.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 = %u \n", timeWindow);
printf("=====================================\n");
///============= sorting file by the serial number & order
int ID[nFile]; /// serial+ order*1000;
int type[nFile];
for( int i = 0; i < nFile; i++){
int snPos = inFileName[i].Index("_"); // first "_"
//snPos = inFileName[i].Index("_", snPos + 1);
int sn = atoi(&inFileName[i][snPos+5]);
TString typeStr = &inFileName[i][snPos+9];
typeStr.Resize(3);
if( typeStr == "PHA" ) type[i] = V1730_DPP_PHA_CODE;
if( typeStr == "PSD" ) type[i] = V1730_DPP_PSD_CODE;
int order = atoi(&inFileName[i][snPos+13]);
ID[i] = sn + order * 1000;
//printf("sn:%d, type:%d (%s), order:%d \n", sn, type[i], typeStr.Data(), order);
}
quickSort(&(ID[0]), &(type[0]), &(inFileName[0]), 0, nFile-1);
for( int i = 0 ; i < nFile; i++){
printf("%d | %6d | %3d | %s \n", i, ID[i], type[i], inFileName[i].Data());
}
///=============== Seperate files
std::vector<int> idCat;
std::vector<std::vector<int>> typeCat;
std::vector<std::vector<TString>> fileCat;
for( int i = 0; i < nFile; i++){
if( ID[i] / 1000 == 0 ) {
std::vector<TString> temp = {inFileName[i]};
std::vector<int> temp2 = {type[i]};
fileCat.push_back(temp);
typeCat.push_back(temp2);
idCat.push_back(ID[i]%1000);
}else{
for( int p = 0; p < (int) idCat.size(); p++){
if( (ID[i] % 1000) == idCat[p] ) {
fileCat[p].push_back(inFileName[i]);
typeCat[p].push_back(type[i]);
}
}
}
}
printf("=====================================\n");
for( int i = 0; i < (int) idCat.size(); i++){
printf("............ %d \n", idCat[i]);
for( int j = 0; j< (int) fileCat[i].size(); j++){
printf("%s | %d\n", fileCat[i][j].Data(), typeCat[i][j]);
}
}
///============= Set Root Tree
outRootFile = new TFile(outFileName, "recreate");
tree = new TTree("tree", outFileName);
tree->Branch("evID", &evID, "event_ID/l");
tree->Branch("multi", &multi, "multi/s");
tree->Branch("bd", bd, "bd[multi]/s");
tree->Branch("ch", ch, "ch[multi]/s");
tree->Branch("e", e, "e[multi]/s");
tree->Branch("e_t", e_t, "e_timestamp[multi]/l");
tree->Branch("e_f", e_f, "e_timestamp[multi]/s");
if( traceOn ) {
arrayTrace = new TClonesArray("TGraph");
tree->Branch("traceLength", traceLength, "traceLength[multi]/s");
tree->Branch("trace", arrayTrace, 2560000);
arrayTrace->BypassStreamer();
}
///============= Open input Files
printf("##############################################\n");
FILE * haha = fopen(fileCat[0][0], "r");
if( haha == NULL ){
printf("#### Cannot open file : %s. Abort.\n", fileCat[0][0].Data());
return -1;
}
fseek(haha, 0L, SEEK_END);
const size_t inFileSize = ftell(haha);
printf("%s | file size : %d Byte = %.2f MB\n", fileCat[0][0].Data(), (int) inFileSize, inFileSize/1024./1024.);
fclose(haha);
Data * data = new Data();
data->DPPType = typeCat[0][0];
data->boardSN = idCat[0];
data->SetSaveWaveToMemory(true);
///============= Main Loop
haha = fopen(inFileName[0], "r");
int countBdAgg = 0;
unsigned long currentTime = 0;
unsigned long oldTime = 0;
char * buffer = NULL;
do{
///========== Get 1 aggreration
oldTime = get_time();
if( debug) printf("*********************** file pos : %d, %lu\n", (int) ftell(haha), oldTime);
unsigned int word[1]; /// 4 bytes
size_t dump = fread(word, 4, 1, haha);
fseek(haha, -4, SEEK_CUR);
short header = ((word[0] >> 28 ) & 0xF);
if( header != 0xA ) break;
unsigned int aggSize = (word[0] & 0x0FFFFFFF) * 4; ///byte
if( debug) printf("Board Agg. has %d word = %d bytes\n", aggSize/4, aggSize);
buffer = new char[aggSize];
dump = fread(buffer, aggSize, 1, haha);
countBdAgg ++;
if( debug) printf("==================== %d Agg\n", countBdAgg);
data->DecodeBuffer(buffer, aggSize, false, 0);
data->ClearBuffer();
if( !data->IsNotRollOverFakeAgg ) continue;
currentTime = get_time();
if( debug) {
printf("~~~~~~~~~~~~~~~~ time used : %lu usec\n", currentTime - oldTime);
data->PrintStat();
}
EventBuilder(data, timeWindow, traceOn, false, debug);
if( debug) printf("---------- event built : %llu \n", evID);
//if( countBdAgg > 74) break;
}while(!feof(haha) && ftell(haha) < inFileSize);
fclose(haha);
printf("=======@@@@@@@@###############============= end of loop \n");
EventBuilder(data, timeWindow, traceOn, true, debug);
tree->Write();
outRootFile->Close();
printf("========================= finsihed.\n");
printf("total events built = %llu \n", evID);
printf("=======> saved to %s \n", outFileName.Data());
}
void EventBuilder(Data * data, const unsigned int timeWin, bool traceOn, bool isLastData, unsigned int verbose){
if( verbose) {
printf("======================== Event Builder \n");
data->PrintAllData();
}
/// find the last event timestamp;
unsigned long long firstTimeStamp = -1;
unsigned long long lastTimeStamp = 0;
unsigned long long smallestLastTimeStamp = -1;
unsigned int maxNumEvent = 0;
for( int chI = 0; chI < MaxNChannels ; chI ++){
if( data->EventIndex[chI] == 0 ) continue;
if( data->Timestamp[chI][0] < firstTimeStamp ) {
firstTimeStamp = data->Timestamp[chI][0];
}
unsigned short ev = data->EventIndex[chI]-1;
if( data->Timestamp[chI][ev] > lastTimeStamp ) {
lastTimeStamp = data->Timestamp[chI][ev];
}
if( ev + 1 > maxNumEvent ) maxNumEvent = ev + 1;
if( data->Timestamp[chI][ev] < smallestLastTimeStamp ){
smallestLastTimeStamp = data->Timestamp[chI][ev];
}
}
if( maxNumEvent == 0 ) return;
if( verbose) printf("================ time range : %llu - %llu, smallest Last %llu\n", firstTimeStamp, lastTimeStamp, smallestLastTimeStamp );
unsigned short lastEv[MaxNChannels] = {0}; /// store the last event number for each ch
unsigned short exhaustedCh = 0; /// when exhaustedCh == MaxNChannels ==> stop
bool singleChannelExhaustedFlag = false; /// when a single ch has data but exhaused ==> stop
do {
/// find the 1st event
int ch1st = -1;
unsigned long long time1st = -1;
for( int chI = 0; chI < MaxNChannels ; chI ++){
if( data->EventIndex[chI] == 0 ) continue;
if( data->EventIndex[chI] <= lastEv[chI] ) continue;
if( data->Timestamp[chI][lastEv[chI]] < time1st ) {
time1st = data->Timestamp[chI][lastEv[chI]];
ch1st = chI;
}
}
if( !isLastData && ((smallestLastTimeStamp - time1st) < NTimeWinForBuffer * timeWin) && maxNumEvent < MaxNData * 0.6 ) break;
if( ch1st > MaxNChannels ) break;
multi ++;
bd[multi-1] = data->boardSN;
ch[multi-1] = ch1st;
e[multi-1] = data->Energy[ch1st][lastEv[ch1st]];
e_t[multi-1] = data->Timestamp[ch1st][lastEv[ch1st]];
e_f[multi-1] = data->fineTime[ch1st][lastEv[ch1st]];
if( traceOn ){
arrayTrace->Clear("C");
traceLength[multi-1] = (unsigned short) data->Waveform1[ch1st][lastEv[ch1st]].size();
///if( verbose )printf("------- trace Length : %u \n", traceLength[multi-1]);
trace = (TGraph *) arrayTrace->ConstructedAt(multi-1, "C");
trace->Clear();
for( int hh = 0; hh < traceLength[multi-1]; hh++){
trace->SetPoint(hh, hh, data->Waveform1[ch1st][lastEv[ch1st]][hh]);
///if( verbose )if( hh % 200 == 0 ) printf("%3d | %u \n", hh, data->Waveform1[ch1st][lastEv[ch1st]][hh]);
}
}
lastEv[ch1st] ++;
/// build the rest of the event
exhaustedCh = 0;
singleChannelExhaustedFlag = false;
for( int chI = ch1st; chI < ch1st + MaxNChannels; chI ++){
unsigned short chX = chI % MaxNChannels;
if( data->EventIndex[chX] == 0 ) {
exhaustedCh ++;
continue;
}
if( data->EventIndex[chX] <= lastEv[chX] ) {
exhaustedCh ++;
singleChannelExhaustedFlag = true;
continue;
}
if( timeWin == 0 ) continue;
for( int ev = lastEv[chX]; ev < data->EventIndex[chX] ; ev++){
if( data->Timestamp[chX][ev] > 0 && (data->Timestamp[chX][ev] - e_t[0] ) < timeWin ) {
multi ++;
bd[multi-1] = data->boardSN;
ch[multi-1] = chX;
e[multi-1] = data->Energy[chX][ev];
e_t[multi-1] = data->Timestamp[chX][ev];
e_f[multi-1] = data->fineTime[chX][ev];
if( traceOn ){
traceLength[multi-1] = (unsigned short) data->Waveform1[chX][ev].size();
trace = (TGraph *) arrayTrace->ConstructedAt(multi-1, "C");
trace->Clear();
for( int hh = 0; hh < traceLength[multi-1]; hh++){
trace->SetPoint(hh, hh, data->Waveform1[chX][ev][hh]);
}
}
lastEv[chX] = ev + 1;
if( lastEv[chX] == data->EventIndex[chX] ) exhaustedCh ++;
}
}
}
if( verbose) {
printf("=============== multi : %d , ev : %llu\n", multi, evID);
for( int ev = 0; ev < multi; ev++){
printf("%3d, ch : %2d, %u, %llu \n", ev, ch[ev], e[ev], e_t[ev]);
}
printf("=============== Last Ev , exhaustedCh %d \n", exhaustedCh);
for( int chI = 0; chI < MaxNChannels ; chI++){
if( lastEv[chI] == 0 ) continue;
printf("%2d, %d %d\n", chI, lastEv[chI], data->EventIndex[chI]);
}
}
/// fill Tree
outRootFile->cd();
tree->Fill();
evID++;
multi = 0;
}while( !singleChannelExhaustedFlag || (exhaustedCh < MaxNChannels) );
///========== clear built data
/// move the last data to the top,
for( int chI = 0; chI < MaxNChannels; chI++){
if( data->EventIndex[chI] == 0 ) continue;
int count = 0;
for( int ev = lastEv[chI] ; ev < data->EventIndex[chI] ; ev++){
data->Energy[chI][count] = data->Energy[chI][ev];
data->Timestamp[chI][count] = data->Timestamp[chI][ev];
data->fineTime[chI][count] = data->fineTime[chI][ev];
count++;
}
int lala = data->EventIndex[chI] - lastEv[chI];
data->EventIndex[chI] = (lala >= 0 ? lala: 0);
}
if( verbose > 0 ) {
printf("&&&&&&&&&&&&&&&&&&&&&&&&&& end of one event build loop\n");
data->PrintAllData();
}
}
//*#############################################################
//*#############################################################
template<typename T> void swap(T * a, T *b ){
T temp = * b;
*b = *a;
*a = temp;
}
int partition(int arr[], int kaka[], TString file[], int start, int end){
int pivot = arr[start];
int count = 0;
for (int i = start + 1; i <= end; i++) {
if (arr[i] <= pivot) count++;
}
/// Giving pivot element its correct position
int pivotIndex = start + count;
swap(&arr[pivotIndex], &arr[start]);
swap(&file[pivotIndex], &file[start]);
swap(&kaka[pivotIndex], &kaka[start]);
/// Sorting left and right parts of the pivot element
int i = start, j = end;
while (i < pivotIndex && j > pivotIndex) {
while (arr[i] <= pivot) {i++;}
while (arr[j] > pivot) {j--;}
if (i < pivotIndex && j > pivotIndex) {
int ip = i++;
int jm = j--;
swap( &arr[ip], &arr[jm]);
swap(&file[ip], &file[jm]);
swap(&kaka[ip], &kaka[jm]);
}
}
return pivotIndex;
}
void quickSort(int arr[], int kaka[], TString file[], int start, int end){
/// base case
if (start >= end) return;
/// partitioning the array
int p = partition(arr, kaka, file, start, end);
/// Sorting the left part
quickSort(arr, kaka, file, start, p - 1);
/// Sorting the right part
quickSort(arr, kaka, file, p + 1, end);
}

11
FSUDAQ
View File

@ -1,11 +0,0 @@
#!/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

1672
FSUDAQ.cpp

File diff suppressed because it is too large Load Diff

149
FSUDAQ.h
View File

@ -1,5 +1,5 @@
#ifndef FSUDAQ_H
#define FSUDAQ_H
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QWidget>
@ -16,47 +16,26 @@
#include "CustomWidgets.h"
#include "Scope.h"
#include "DigiSettingsPanel.h"
#include "SingleSpectra.h"
#include "ClassInfluxDB.h"
#include "analyzers/Analyser.h"
#include "CanvasClass.h"
#include "influxdb.h"
class ScalarWorker; //Forward declaration
//^#===================================================== FSUDAQ
class FSUDAQ : public QMainWindow{
//^#===================================================== MainWindow
class MainWindow : public QMainWindow{
Q_OBJECT
public:
FSUDAQ(QWidget *parent = nullptr);
~FSUDAQ();
MainWindow(QWidget *parent = nullptr);
~MainWindow();
void closeEvent(QCloseEvent * event){
if( scope ) {
delete scope;
scope = nullptr;
}
if( digiSettings ) {
delete digiSettings;
digiSettings = nullptr;
}
if( singleHistograms ) {
delete singleHistograms;
singleHistograms = nullptr;
}
if( onlineAnalyzer ) {
delete onlineAnalyzer;
onlineAnalyzer = nullptr;
}
if( scope ) scope->close();
if( digiSettings ) digiSettings->close();
if( canvas ) canvas->close();
event->accept();
}
public slots:
void UpdateScalar();
private slots:
void OpenDataPath();
void OpenRecord();
void UpdateRecord();
void LoadProgramSettings();
void SaveProgramSettings();
void LoadLastRunFile();
@ -69,6 +48,7 @@ private slots:
void SetupScalar();
void CleanUpScalar();
void OpenScalar();
void UpdateScalar();
void StartACQ();
void StopACQ();
@ -80,79 +60,46 @@ private slots:
void OpenDigiSettings();
void OpenSingleHistograms();
void OpenAnalyzer();
void OpenCanvas();
void UpdateAllPanels(int panelID);
void SetUpInflux();
void CheckElog();
void WriteElog(QString htmlText, QString subject, QString category, int runNumber);
void AppendElog(QString appendHtmlText);
void SetSyncMode();
void SetAndLockInfluxElog();
private:
Digitizer ** digi;
unsigned int nDigi;
bool isACQStarted;
QString programSettingsFilePath;
QString rawDataPath;
QString prefix;
unsigned int runID;
int elogID;
unsigned int elogID;
QString influxIP;
QString dataBaseName;
QString elogIP;
RComboBox * cbOpenDigitizers;
RComboBox * cbOpenMethod;
//QPushButton * bnOpenDigitizers;
QPushButton * bnOpenDigitizers;
QPushButton * bnCloseDigitizers;
QPushButton * bnOpenScope;
QPushButton * bnDigiSettings;
//QPushButton * bnAnalyzer;
RComboBox * cbAnalyzer;
QPushButton * bnOpenScaler;
QPushButton * bnStartACQ;
QPushButton * bnStopACQ;
QPushButton * bnSync;
QPushButton * bnCanvas;
QTimer * runTimer;
bool breakAutoRepeat;
bool needManualComment;
QMetaObject::Connection runTimerConnection;
//@----- influx
InfluxDB * influx;
QString influxIP;
QString dataBaseName;
QLineEdit * leInfluxIP;
QLineEdit * leDatabaseName;
QPushButton * bnLock;
QString influxToken;
short scalarCount;
//@----- Elog
QString elogIP;
QString elogPort;
QString elogName;
QString elogUser;
QString elogPWD;
QLineEdit * leElogIP;
QLineEdit * leElogName;
QCheckBox * chkInflux;
QCheckBox * chkElog;
//@----- log msg
QPlainTextEdit * logInfo;
@ -174,76 +121,26 @@ private:
//@----- Scalar
QMainWindow * scalar;
QGridLayout * scalarLayout;
TimingThread * scalarTimingThread;
// QThread * scalarThread;
// ScalarWorker * scalarWorker;
// QTimer * scalarTimer;
// TimingThread * scalarThread;
TimingThread * scalarThread;
QLineEdit *** leTrigger; // need to delete manually
QLineEdit *** leAccept; // need to delete manually
QPushButton * runStatus[MaxNDigitizer];
QLabel * lbLastUpdateTime;
QLabel * lbScalarACQStatus;
QLabel * lbAggCount[MaxNDigitizer];
QLabel * lbFileSize[MaxNDigitizer];
QLabel * lbTotalFileSize;
//@----- Run Record
QMainWindow * runRecord;
QStandardItemModel *model;
QTableView * tableView;
//@----- ACQ
ReadDataThread ** readDataThread;
//@----- Scope
Scope * scope;
//@----- DigiSettings
DigiSettingsPanel * digiSettings;
//@----- SingleSpectra
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);
}
}
//@----- Canvas
Canvas * canvas;
TimingThread * histThread;
};
//^======================== 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

@ -6,15 +6,14 @@ TEMPLATE = app
TARGET = FSUDAQ_Qt6
INCLUDEPATH += .
QT += core widgets charts printsupport
QT += core widgets charts
#QMAKE_CXXFLAGS += `root-config --cflags --glibs`
#LIBS += -lCAENDigitizer `root-config --cflags --glibs`
#QMAKE_CXXFLAGS += -g
LIBS += -lCAENDigitizer -lcurl
#==== for enable GDB debug
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.
# Please consult the documentation of the deprecated API in order to know
@ -25,36 +24,19 @@ QMAKE_CFLAGS_RELEASE = -O0
# Input
HEADERS += ClassData.h \
ClassDigitizer.h \
ClassInfluxDB.h\
CustomThreads.h \
CustomWidgets.h \
DigiSettingsPanel.h \
FSUDAQ.h \
Histogram1D.h \
Histogram2D.h \
Hit.h \
macro.h \
MultiBuilder.h \
qcustomplot.h \
RegisterAddress.h \
influxdb.h\
Scope.h \
SingleSpectra.h \
analyzers/Analyser.h \
analyzers/CoincidentAnalyzer.h \
analyzers/Cross.h\
analyzers/EncoreAnalyzer.h \
analyzers/Isotope.h \
analyzers/SplitPoleAnalyzer.h \
analyzers/MUSICAnalyzer.h \
analyzers/NeutronGamma.h
CanvasClass.h
SOURCES += ClassDigitizer.cpp \
DigiSettingsPanel.cpp \
FSUDAQ.cpp \
main.cpp \
ClassInfluxDB.cpp\
influxdb.cpp\
Scope.cpp \
SingleSpectra.cpp \
MultiBuilder.cpp \
qcustomplot.cpp \
analyzers/Analyser.cpp
CanvasClass.cpp

View File

@ -1,378 +0,0 @@
#ifndef HISTOGRAM_1D_H
#define HISTOGRAM_1D_H
#include "qcustomplot.h"
#include "macro.h"
#define MaxNHist 10
//^==============================================
//^==============================================
class Histogram1D : public QCustomPlot{
Q_OBJECT
public:
Histogram1D(QString title, QString xLabel, int xbin, double xmin, double xmax, QWidget * parent = nullptr) : QCustomPlot(parent){
// 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);
xAxis->setLabel(xLabel);
legend->setVisible(true);
QPen borderPen = legend->borderPen();
borderPen.setWidth(0);
borderPen.setColor(Qt::transparent);
legend->setBorderPen(borderPen);
legend->setFont(QFont("Helvetica", 9));
addGraph();
graph(0)->setName(title);
graph(0)->setPen(QPen(Qt::blue));
graph(0)->setBrush(QBrush(QColor(0, 0, 255, 20)));
xAxis2->setVisible(true);
xAxis2->setTickLabels(false);
yAxis2->setVisible(true);
yAxis2->setTickLabels(false);
// make left and bottom axes always transfer their ranges to right and top axes:
connect(xAxis, SIGNAL(rangeChanged(QCPRange)), xAxis2, SLOT(setRange(QCPRange)));
connect(yAxis, SIGNAL(rangeChanged(QCPRange)), yAxis2, SLOT(setRange(QCPRange)));
graph(0)->setData(xList, yList[0]);
//setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);
//setInteractions( QCP::iRangeDrag | QCP::iRangeZoom );
//setSelectionRectMode(QCP::SelectionRectMode::srmZoom);
rescaleAxes();
yAxis->setRangeLower(0);
yAxis->setRangeUpper(10);
for( int i = 0; i < 3; i ++){
txt[i] = new QCPItemText(this);
txt[i]->setPositionAlignment(Qt::AlignLeft);
txt[i]->position->setType(QCPItemPosition::ptAxisRectRatio);
txt[i]->position->setCoords(0.1, 0.1 + 0.1*i);;
txt[i]->setFont(QFont("Helvetica", 9));
}
txt[0]->setText("Under Flow : 0");
txt[1]->setText("Total Entry : 0");
txt[2]->setText("Over Flow : 0");
usingMenu = false;
connect(this, &QCustomPlot::mouseMove, this, [=](QMouseEvent *event){
double x = this->xAxis->pixelToCoord(event->pos().x());
double bin = (x - xMin)/dX;
double z = yList[0][2*qFloor(bin) + 1];
QString coordinates = QString("Bin: %1, Value: %2").arg(qFloor(bin)).arg(z);
QToolTip::showText(event->globalPosition().toPoint(), coordinates, this);
});
connect(this, &QCustomPlot::mousePress, this, [=](QMouseEvent * event){
if (event->button() == Qt::LeftButton && !usingMenu){
setSelectionRectMode(QCP::SelectionRectMode::srmZoom);
}
if (event->button() == Qt::RightButton) {
usingMenu = true;
setSelectionRectMode(QCP::SelectionRectMode::srmNone);
QMenu menu(this);
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);
yAxis->setRangeLower(0);
yAxis->setRangeUpper(yMax * 1.2 > 10 ? yMax * 1.2 : 10);
replot();
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());
}
replot();
usingMenu = false;
}
//*========================================== Rebin
if( selectedAction == a4 ){
QDialog dialog(this);
dialog.setWindowTitle("Rebin histogram");
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(xBin));
lineEdit[1]->setText(QString::number(xMin));
lineEdit[2]->setText(QString::number(xMax));
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 ){
Rebin((int)number[0], number[1], number[2]);
emit ReBinned();
UpdatePlot();
}
}
//*========================================== 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;
}else{
this->yAxis->setScaleType(QCPAxis::stLinear);
isLogY = false;
}
this->replot();
}
}
});
}
int GetNBin() const {return xBin;}
double GetXMin() const {return xMin;}
double GetXMax() const {return xMax;}
void SetColor(QColor color, unsigned short ID = 0) {
DebugPrint("%s", "Histogram1D");
graph(ID)->setPen(QPen(color));
QColor haha = color;
haha.setAlpha(20);
graph(ID)->setBrush(QBrush(haha));
}
void AddDataList(QString title, QColor color){
nData ++;
addGraph();
graph(nData - 1)->setName(title);
SetColor(color, nData-1);
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)->setVisible(showHist[ID]);
graph(ID)->setData(xList, yList[ID]);
}
xAxis->setRangeLower(xMin);
xAxis->setRangeUpper(xMax);
yAxis->setRangeLower(0);
yAxis->setRangeUpper(yMax * 1.2 > 10 ? yMax * 1.2 : 10);
replot();
}
void Clear(){
DebugPrint("%s", "Histogram1D");
for( int ID = 0 ; ID < nData; ID ++) {
for( int i = 0; i < xList.count(); i++) yList[ID][i] = 0;
}
yMax = 0;
txt[0]->setText("Under Flow : 0");
txt[1]->setText("Total Entry : 0");
txt[2]->setText("Over Flow : 0");
totalEntry = 0;
underFlow = 0;
overFlow = 0;
UpdatePlot();
}
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);
xList.clear();
for( int i = 0 ; i < nData ; i ++) yList[i].clear();
for( int i = 0; i <= xBin; i ++ ){
xList.append(xMin + i*dX-(dX)*0.000001);
xList.append(xMin + i*dX);
for( int ID = 0 ; ID < nData; ID ++ ){
yList[ID].append(0);
yList[ID].append(0);
}
}
yMax = 0;
totalEntry = 0;
underFlow = 0;
overFlow = 0;
if( txt[0] ) txt[0]->setText("Under Flow : 0");
if( txt[1] ) txt[1]->setText("Total Entry : 0");
if( txt[2] ) txt[2]->setText("Over Flow : 0");
}
void Fill(double value, unsigned int ID = 0){
// DebugPrint("%s", "Histogram1D");
if( ID == 0 ){
totalEntry ++;
txt[1]->setText("Total Entry : "+ QString::number(totalEntry));
if( value < xMin ) {
underFlow ++;
txt[0]->setText("Under Flow : "+ QString::number(underFlow));
return;
}
if( value > xMax ) {
overFlow ++;
txt[2]->setText("Over Flow : "+ QString::number(overFlow));
return;
}
}else{
if( value < xMin || value > xMax ) return;
}
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( showHist[ID] && yList[ID][index1] > yMax ) yMax = yList[ID][index1];
}
void Print(unsigned int ID = 0){
for( int i = 0; i < xList.count(); i++){
printf("%f %f\n", xList[i], yList[ID][i]);
}
}
signals:
void ReBinned(); //ONLY for right click rebin
private:
double xMin, xMax, dX;
int xBin;
double yMax;
int totalEntry;
int underFlow;
int overFlow;
bool isLogY;
unsigned short nData;
QVector<double> xList;
QVector<double> yList[MaxNHist];
QCPItemText * txt[3];
bool usingMenu;
bool showHist[MaxNHist];
};
#endif

View File

@ -1,810 +0,0 @@
#ifndef HISTOGRAM_2D_H
#define HISTOGRAM_2D_H
#include "qcustomplot.h"
#include "macro.h"
const QList<QPair<QColor, QString>> colorCycle = { {QColor(Qt::red), "Red"},
{QColor(Qt::blue), "Blue"},
{QColor(Qt::darkGreen), "Dark Geen"},
{QColor(Qt::darkCyan), "Dark Cyan"},
{QColor(Qt::darkYellow), "Drak Yellow"},
{QColor(Qt::magenta), "Magenta"},
{QColor(Qt::darkMagenta), "Dark Magenta"},
{QColor(Qt::gray), "Gray"}};
//^==============================================
//^==============================================
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,
QString defaultPath = QDir::homePath());
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(){ colorMap->rescaleDataRange(true); replot(); }
void Clear(); // Clear Data and histrogram
void Fill(double x, double y);
void DrawCut();
void ClearAllCuts();
QList<QPolygonF> GetCutList() const{return cutList;} // this list may contain empty element
QList<int> GetCutEntryList() const{ return cutEntryList;}
QList<QString> GetCutNameList() const { return cutNameList;}
void PrintCutEntry() const;
double GetXNBin() const {return xBin;}
double GetXMin() const {return xMin;}
double GetXMax() const {return xMax;}
double GetYNBin() const {return yBin;}
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;
bool isChannelMap;
int tickStep;
bool isLogZ;
QCPColorMap * colorMap;
QCPColorScale *colorScale;
bool usingMenu;
int entry[3][3]; // overflow counter, entrt[1][1] is entry in the plot;
QCPItemRect * box[3][3];
QCPItemText * txt[3][3];
QPolygonF tempCut;
int tempCutID; // only incresing;
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;
QCPItemLine * line;
double oldMouseX = 0.0, oldMouseY = 0.0;
bool isBusy;
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;
int xIndex, yIndex;
colorMap->data()->coordToCell(x, y, &xIndex, &yIndex);
//printf("%f, %d %d| %f, %d %d\n", x, xIndex, xBin, y, yIndex, yBin);
int xk = 1, yk = 1;
if( xIndex < 0 ) xk = 0;
if( xIndex >= xBin ) xk = 2;
if( yIndex < 0 ) yk = 2;
if( yIndex >= yBin ) yk = 0;
entry[xk][yk] ++;
txt[xk][yk]->setText(QString::number(entry[xk][yk]));
if( xk == 1 && yk == 1 ) {
double value = colorMap->data()->cell(xIndex, yIndex);
if( std::isnan(value) ){
colorMap->data()->setCell(xIndex, yIndex, 1);
}else{
colorMap->data()->setCell(xIndex, yIndex, value + 1);
}
for( int i = 0; i < cutList.count(); i++){
if( cutList[i].isEmpty() ) continue;
if( cutList[i].containsPoint(QPointF(x,y), Qt::OddEvenFill) ) cutEntryList[i] ++;
}
}
}
inline void Histogram2D::Rebin(int xbin, double xmin, double xmax, int ybin, double ymin, double ymax){
// DebugPrint("%s", "Histogram2D");
xMin = xmin;
xMax = xmax;
yMin = ymin;
yMax = ymax;
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));
for( int i = 0; i < xBin; i++){
for( int j = 0; j < yBin; j++){
colorMap->data()->setCell(i, j, NAN);
}
}
if( isChannelMap ){
QCPAxis * xAxis = colorMap->keyAxis();
xAxis->ticker()->setTickCount(xbin/tickStep);
xAxis->ticker()->setTickOrigin(0);
}
for( int i = 0; i < 3; i ++){
for( int j = 0; j < 3; j ++){
entry[i][j] = 0;
if( txt[i][j] ) txt[i][j]->setText("0");
}
}
rescaleAxes();
UpdatePlot();
}
inline void Histogram2D::RebinY(int ybin, double ymin, double ymax){
Rebin(xBin-2, xMin, xMax, ybin, ymin, ymax);
}
inline void Histogram2D::Clear(){
DebugPrint("%s", "Histogram2D");
for( int i = 0; i < 3; i ++){
for( int j = 0; j < 3; j ++){
entry[i][j] = 0;
txt[i][j]->setText("0");
}
}
colorMap->data()->clear();
colorMap->data()->setSize(xBin, yBin);
colorMap->data()->setRange(QCPRange(xMin, xMax), QCPRange(yMin, yMax));
for( int i = 0; i < xBin; i++){
for( int j = 0; j < yBin; j++){
colorMap->data()->setCell(i, j, NAN);
}
}
UpdatePlot();
}
inline void Histogram2D::ClearAllCuts(){
DebugPrint("%s", "Histogram2D");
numCut = 0;
tempCutID = -1;
lastPlottableID = -1;
cutList.clear();
cutIDList.clear();
for( int i = cutTextIDList.count() - 1; i >= 0 ; i--){
if( cutTextIDList[i] < 0 ) continue;
removeItem(cutTextIDList[i]);
removePlottable(plottableIDList[i]);
}
replot();
cutTextIDList.clear();
plottableIDList.clear();
cutNameList.clear();
cutEntryList.clear();
}
inline void Histogram2D::PrintCutEntry() const{
DebugPrint("%s", "Histogram2D");
if( numCut == 0 ) return;
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]);
}
}
inline void Histogram2D::DrawCut(){
DebugPrint("%s", "Histogram2D");
//The histogram is the 1st plottable.
// the lastPlottableID should be numCut+ 1
if( lastPlottableID != numCut ){
removePlottable(lastPlottableID);
}
if(tempCut.size() > 0) {
QCPCurve *polygon = new QCPCurve(xAxis, yAxis);
lastPlottableID = plottableCount() - 1;
int colorID = tempCutID% colorCycle.count();
QPen pen(colorCycle[colorID].first);
pen.setWidth(1);
polygon->setPen(pen);
QVector<QCPCurveData> dataPoints;
for (const QPointF& point : tempCut) {
dataPoints.append(QCPCurveData(dataPoints.size(), point.x(), point.y()));
}
polygon->data()->set(dataPoints, false);
}
replot();
// qDebug() << "Plottable count : " << plottableCount() << ", cutList.count :" << cutList.count() << ", cutID :" << lastPlottableID;
}
inline void Histogram2D::rightMouseClickMenu(QMouseEvent * event){
DebugPrint("%s", "Histogram2D");
usingMenu = true;
setSelectionRectMode(QCP::SelectionRectMode::srmNone);
QMenu *menu = new QMenu(this);
menu->setAttribute(Qt::WA_DeleteOnClose);
QAction * a1 = menu->addAction("UnZoom");
QAction * a6 = menu->addAction("Set/UnSet Log-Z");
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();
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;
QString haha = "";
menu->addAction("Delete " + cutNameList[i] + " ["+ colorCycle[cutIDList[i]%colorCycle.count()].second+"]");
}
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();
}
if( selectedAction == a2 ) {
Clear();
}
if( selectedAction == a3 ){
for( int i = 0; i < 3; i ++ ){
for( int j = 0; j < 3; j ++ ){
box[i][j]->setVisible( !box[i][j]->visible());
txt[i][j]->setVisible( !txt[i][j]->visible());
}
}
replot();
}
if( selectedAction == a4){
rightMouseClickRebin();
}
if( selectedAction == a5 ){
tempCut.clear();
tempCutID ++;
isDrawCut= true;
numCut ++;
}
if( selectedAction == a6){
if( !isLogZ ){
colorMap->setDataScaleType(QCPAxis::stLogarithmic);
isLogZ = true;
}else{
colorMap->setDataScaleType(QCPAxis::stLinear);
isLogZ = false;
}
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();
int index1 = haha.indexOf("-");
int index2 = haha.indexOf("[");
int cutID = haha.mid(index1+1, index2-index1-1).remove(' ').toInt();
removeItem(cutTextIDList[cutID]);
removePlottable(plottableIDList[cutID]);
replot();
numCut --;
cutList[cutID].clear();
cutIDList[cutID] = -1;
cutTextIDList[cutID] = -1;
plottableIDList[cutID] = -1;
cutNameList[cutID] = "";
cutEntryList[cutID] = -1;
for( int i = cutID + 1; i < cutTextIDList.count() ; i++){
cutTextIDList[i] --;
plottableIDList[i] --;
}
if( numCut == 0 ){
tempCutID = -1;
lastPlottableID = -1;
cutList.clear();
cutIDList.clear();
cutTextIDList.clear();
plottableIDList.clear();
cutNameList.clear();
cutEntryList.clear();
}
}
usingMenu = false;
}
inline void Histogram2D::rightMouseClickRebin(){
DebugPrint("%s", "Histogram2D");
QDialog dialog(this);
dialog.setWindowTitle("Rebin histogram");
QFormLayout layout(&dialog);
QLabel * info = new QLabel(&dialog);
info->setStyleSheet("color:red;");
info->setText("This will also clear histogram!!");
layout.addRow(info);
QStringList nameListX = {"Num. x-Bin", "x-Min", "x-Max"};
QLineEdit* lineEditX[3];
for (int i = 0; i < 3; ++i) {
lineEditX[i] = new QLineEdit(&dialog);
layout.addRow(nameListX[i] + " : ", lineEditX[i]);
}
lineEditX[0]->setText(QString::number(xBin-2));
lineEditX[1]->setText(QString::number(xMin));
lineEditX[2]->setText(QString::number(xMax));
QStringList nameListY = {"Num. y-Bin", "y-Min", "y-Max"};
QLineEdit* lineEditY[3];
for (int i = 0; i < 3; ++i) {
lineEditY[i] = new QLineEdit(&dialog);
layout.addRow(nameListY[i] + " : ", lineEditY[i]);
}
lineEditY[0]->setText(QString::number(yBin-2));
lineEditY[1]->setText(QString::number(yMin));
lineEditY[2]->setText(QString::number(yMax));
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][2];
QObject::connect(&buttonBox, &QDialogButtonBox::accepted, [&]() {
int OKcount = 0;
bool conversionOk = true;
for( int i = 0; i < 3; i++ ){
number[i][0] = lineEditX[i]->text().toDouble(&conversionOk);
if( conversionOk ){
OKcount++;
}else{
msg->setText(nameListX[i] + " is invalid.");
return;
}
}
for( int i = 0; i < 3; i++ ){
number[i][1] = lineEditY[i]->text().toDouble(&conversionOk);
if( conversionOk ){
OKcount++;
}else{
msg->setText(nameListY[i] + " is invalid.");
return;
}
}
if( OKcount == 6 ) {
if( number[0][0] <= 0 ) {
msg->setText( nameListX[0] + " is zero or negative" );
return;
}
if( number[0][0] <= 0 ) {
msg->setText( nameListX[0] + " is zero or negative" );
return;
}
if( number[2][0] > number[1][0] && number[2][1] > number[1][1] ) {
dialog.accept();
}else{
if( number[2][0] > number[1][0] ){
msg->setText(nameListX[2] + " is smaller than " + nameListX[1]);
}
if( number[2][1] > number[1][1] ){
msg->setText(nameListY[2] + " is smaller than " + nameListY[1]);
}
}
}
});
QObject::connect(&buttonBox, &QDialogButtonBox::rejected, [&]() { dialog.reject();});
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]);
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

88
Hit.h
View File

@ -1,88 +0,0 @@
#ifndef Hit_H
#define Hit_H
#include <vector>
class Hit{
public:
unsigned short sn;
unsigned short ch;
unsigned short energy;
unsigned short energy2;
unsigned long long timestamp;
unsigned short fineTime;
bool pileUp;
unsigned short traceLength;
std::vector<short> trace;
Hit(){
Clear();
}
void Clear(){
sn = 0;
ch = 0;
energy = 0;
energy2 = 0;
timestamp = 0;
fineTime = 0;
traceLength = 0;
pileUp = false;
trace.clear();
}
void Print(){
printf("(%5d, %2d) %6d %16llu, %6d, %d, %5ld\n", sn, ch, energy, timestamp, fineTime, pileUp, trace.size());
}
void PrintTrace(){
for( unsigned short i = 0; i < traceLength; i++){
printf("%3u | %6d \n", i, trace[i]);
}
}
// 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");
}
};
#endif

674
LICENSE
View File

@ -1,674 +0,0 @@
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>.

39
Makefile_test Normal file
View File

@ -0,0 +1,39 @@
########################################################################
#
#
#########################################################################
CC = g++
#COPTS = -fPIC -DLINUX -O2 -std=c++17 -lpthread
COPTS = -fPIC -DLINUX -g -std=c++17 -lpthread
CAENLIBS = -lCAENDigitizer
ROOTLIBS = `root-config --cflags --glibs`
OBJS = ClassDigitizer.o
ALL = test test_indep EventBuilder
#########################################################################
all : $(ALL)
clean :
/bin/rm -f $(OBJS) $(ALL)
ClassDigitizer.o : ClassDigitizer.cpp ClassDigitizer.h RegisterAddress.h macro.h ClassData.h
$(CC) $(COPTS) -c ClassDigitizer.cpp
test : test.cpp ClassDigitizer.o
@echo "--------- making test"
$(CC) $(COPTS) -o test test.cpp ClassDigitizer.o $(CAENLIBS) $(ROOTLIBS)
test_indep : test_indep.cpp RegisterAddress.h macro.h
@echo "--------- making test_indep"
$(CC) $(COPTS) -o test_indep test_indep.cpp $(CAENLIBS)
EventBuilder : EventBuilder.cpp ClassData.h
@echo "--------- making EventBuilder"
$(CC) $(COPTS) -o EventBuilder EventBuilder.cpp $(CAENLIBS) $(ROOTLIBS)

View File

@ -1,474 +0,0 @@
#include "MultiBuilder.h"
#include <algorithm>
MultiBuilder::MultiBuilder(Data ** multiData, std::vector<int> type, std::vector<int> sn) : nData(type.size()){
DebugPrint("%s", "MultiBuilder");
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();
// for( int i = 0; i < nData; i++){
// printf("sn: %d, numCh : %d \n", snList[i], data[i]->GetNChannel());
// }
}
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);
timeWindow = 100;
leftOverTime = 100;
breakTime = -1;
timeJump = 1e8;
lastEventTime = 0;
forceStop = false;
ClearEvents();
}
MultiBuilder::~MultiBuilder(){
DebugPrint("%s", "MultiBuilder");
}
void MultiBuilder::ClearEvents(){
DebugPrint("%s", "MultiBuilder");
eventIndex = -1;
eventBuilt = 0;
totalEventBuilt = 0;
for( int i = 0; i < MaxNEvent; i++) events[i].clear();
for( int i = 0; i < MaxNDigitizer; i++){
for( int j = 0; j < MaxNChannels; j++){
nextIndex[i][j] = -1;
chExhaused[i][j] = false;
lastBackWardIndex[i][j] = 0;
}
earlistDigi = -1;
earlistCh = -1;
earlistTime = -1;
latestTime = 0;
nExhaushedCh = 0;
}
}
void MultiBuilder::PrintStat(){
DebugPrint("%s", "MultiBuilder");
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 | %7ld\n", i, snList[i], ch, nextIndex[i][ch]);
}
}
}
void MultiBuilder::PrintAllEvent(){
DebugPrint("%s", "MultiBuilder");
printf("Total number of evet built : %ld\n", totalEventBuilt);
for( int i = 0; i < totalEventBuilt; i++){
printf("%5d ------- size: %ld\n", i, events[i].size());
for( int j = 0; j < (int)events[i].size(); j++){
events[i][j].Print();
}
}
}
//^############################################### forward event builder
void MultiBuilder::FindEarlistTimeAndCh(bool verbose){
DebugPrint("%s", "MultiBuilder");
earlistTime = -1;
earlistDigi = -1;
earlistCh = -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 ++){
{// 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 || nextIndex[i][ch] > data[i]->GetAbsDataIndex(ch)) {
nExhaushedCh ++;
chExhaused[i][ch] = true;
continue;
}
}
if( nextIndex[i][ch] == -1 ) nextIndex[i][ch] = 0;
unsigned long long time = data[i]->GetTimestamp(ch, nextIndex[i][ch]);
if( time < earlistTime ) {
earlistTime = time;
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::FindEarlistTimeAmongLastData(bool verbose){
DebugPrint("%s", "MultiBuilder");
latestTime = -1;
latestCh = -1;
latestDigi = -1;
for( int i = 0; i < nData; i++){
for( unsigned ch = 0; ch < data[i]->GetNChannel(); ch++ ){
if( chExhaused[i][ch] ) continue;
int index = data[i]->GetDataIndex(ch);
if( index == -1 ) continue;
if( data[i]->GetTimestamp(ch, index) < latestTime ) {
latestTime = data[i]->GetTimestamp(ch, index);
latestCh = ch;
latestDigi = i;
}
}
}
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");
latestTime = 0;
latestCh = -1;
latestDigi = -1;
for( int i = 0; i < nData; i++){
// printf("%s | digi-%d-th | %d\n", __func__, i, data[i]->GetNChannel());
for( unsigned ch = 0; ch < data[i]->GetNChannel(); ch++ ){
int index = data[i]->GetDataIndex(ch);
// printf("ch-%2d | index : %d \n", ch, index);
if( index == -1 ) continue;
if( data[i]->GetTimestamp(ch, index) > latestTime ) {
latestTime = data[i]->GetTimestamp(ch, index);
latestCh = ch;
latestDigi = i;
}
}
}
if( verbose ) printf("%s | bd : %d, ch : %d, %lld \n", __func__, latestDigi, latestCh, latestTime);
}
void MultiBuilder::BuildEventsBackWard(int maxNumEvent, bool verbose){
DebugPrint("%s", "MultiBuilder");
//skip trace, and only build for maxNumEvent events max
// 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]->GetAbsDataIndex(i);
}
}
FindLatestTimeAndCh(verbose);
//========== build event
eventBuilt = 0;
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 + latestDigi) % nData;
const int numCh = data[k]->GetNChannel();
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){
nExhaushedCh ++;
chExhaused[bd][ch] = true;
continue;
}
do{
unsigned long long time = data[bd]->GetTimestamp(ch, nextIndex[bd][ch]);
if( time <= latestTime && (latestTime - time <= timeWindow)){
em.sn = snList[bd];
em.ch = ch;
em.energy = data[bd]->GetEnergy(ch, nextIndex[bd][ch]);
em.timestamp = time;
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] < 0 && data[bd]->GetLoopIndex(ch) > 0 ) nextIndex[bd][ch] = dataSize[bd] - 1;
}else{
break;
}
if( timeWindow == 0 ) break;
}while(true);
if( timeWindow == 0 ) break;
}
if( timeWindow == 0 ) break;
}
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++){
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("%5d, %02d | %7ld | %5d %llu \n", sn, chxxx, nextIndex[bd][chxxx], events[eventIndex][i].energy, events[eventIndex][i].timestamp);
}
}
}while(nExhaushedCh < numTotCh && eventBuilt < maxNumEvent);
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

@ -1,92 +0,0 @@
#ifndef MuLTI_BUILDER_H
#define MuLTI_BUILDER_H
#include "ClassData.h"
#include "Hit.h"
#define MaxNEvent 100000 // circular, this number should be at least nDigi * MaxNChannel * MaxNData
class MultiBuilder {
public:
MultiBuilder(Data ** multiData, std::vector<int> type, std::vector<int> sn);
MultiBuilder(Data * singleData, int type, int sn);
~MultiBuilder();
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 nanosec) {leftOverTime = nanosec;}
unsigned long long GetLeftOverTime() const{return leftOverTime;}
void SetBreakTime(unsigned long long nanosec) {breakTime = nanosec;}
unsigned long long GetBreakTime() const{return breakTime;}
unsigned int GetNumOfDigitizer() const {return nData;}
std::vector<int> GetDigiIDList() const {return idList;}
void BuildEvents(bool isFinal = false, bool skipTrace = false, bool verbose = false);
void BuildEventsBackWard(int maxNumEvent = 100, bool verbose = false); // always skip trace, for faster online building
void ClearEvents();
void PrintStat();
void PrintAllEvent();
long eventIndex;
long eventBuilt; // reset once call BuildEvents()
long totalEventBuilt;
std::vector<Hit> events[MaxNEvent];
private:
std::vector<int> typeList;
std::vector<int> snList;
std::vector<int> idList;
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;
unsigned short timeWindow;
unsigned long long leftOverTime;
unsigned long long breakTime; // timestamp for breaking the event builder
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];
long nextIndex[MaxNDigitizer][MaxNChannels]; // loopIndex * dataSize + index
int nExhaushedCh;
bool chExhaused[MaxNDigitizer][MaxNChannels];
void FindEarlistTimeAndCh(bool verbose = false); // search through the nextIndex
unsigned long long earlistTime;
int earlistDigi;
int earlistCh;
void FindLatestTimeAndCh(bool verbose = false); // search through the nextIndex
unsigned long long latestTime;
int latestDigi;
int latestCh;
void FindEarlistTimeAmongLastData(bool verbose = false);
void FindLatestTimeOfData(bool verbose = false);
int lastBackWardIndex[MaxNDigitizer][MaxNChannels]; // abs. index
bool forceStop;
};
#endif

182
README.md
View File

@ -1,195 +1,31 @@
# Discord
https://discord.gg/xVsRhNZF8G
# Introduction
This is a DAQ for 1st gen CAEN digitizer for
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 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
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.
An online analyzer class is created as a template for online analysis. An example is the SplitPoleAnalyzer.h. It demo a 2-D histogram and a 1-D histogram, and the way to output the rates of cuts to influxDB.
<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
- (line 1) raw data path, where the data will be stored.
- (line 2) the influxDB v1.8+ IP
- (line 3) the database name
- (line 4) the influxDB token (for v2.0+)
- (line 5) the elog IP
- (line 6) the elog logbook name
- (line 7) elog user name
- (line 8) elog user password
If no programSettings.txt is found. The program can still search for all digitizers that connected using optical cable.
Missing the raw data path will disable save data run, but still can start the ACQ. Missing InfluxDB (elog) variables will disable influxDB (elog).
## Keyboard control
- F4 open any drop-down list
- tab for next element
- crtl+tab for previous element
- space for "press a button"
- alt + tab for switching different windows
- up/down arrow for increase/decrease number (<span style="color:blue">Blue Tex</span> = value not set, <span style="color:red">Red Tex</span> = value cannot set)
## Data folder
User must setup the data path for data take. Without the data path, user still can run the DAQ. Inside the data path, when a run is started there are
- RunTimestamp.dat <- this store the timestamps and comments for all runs
- RunTimestamp.csv <- csv format for the RunTimestamp.dat, easy for inport to excel
- lastRun.sh <- some data for bash script
- *.fsu <- all data file
- *.bin <- setting file
# ToDo
- Gaussians fitting for 1D Histogra
- Save Histogram?
It has scope (updated every half-sec), allow full control of the digitizer (except LVDS), and allow saving waevform.
# Required / Development enviroment
Ubuntu 22.04
- CAENVMELib v3.3 +
- CAENCOmm v1.5.3 +
- CAENDigitizer v2.17.1 +
- CAEN A3818 Driver v1.6.8 +
- CAENUSBdrv v1.5.5 + (for V57XX digitizer with USB connection)
CAENVMELib_v3.3
- qt6-base-dev
- libqt6charts6-dec
- libcurl4-openssl-dev
- elog
CAENCOmm_v1.5.3
The CAEN Libraries need to download and install manually. The other libraries can be installed using the following command:
CAENDigitizer_v2.17.1
`sudo apt install qt6-base-dev libqt6charts6-dev libcurl4-openssl-dev elog`
The elog installed using apt is 3.1.3. If a higher version is needed. Please go to https://elog.psi.ch/elog/
The libcurl4 is need for pushing data to InfluxDB v1.8+
InfluxDB can be installed via `sudo apt install influxdb` for v1.8. the v2.0+ can be manually installed from the InfluxDB webpage https://docs.influxdata.com/influxdb/v2/.
The QCustomPlot (https://www.qcustomplot.com/index.php/introduction) source files are already included in the repository.
## For A4818 optical-USB
need to install the A4818 driver.
Make sure connect the optical fiber before switch on the digitizer(s). If unplug the optical fiber and reconnect, need to restart the digitizer(s).
## For A5818 PCI gen 3
need to install CAENVMELib v4.0 +
## For Raspberry Pi installation
All required CAEN Libraries support ARM archetect, so installation of those would not be a problem.
THe libqt6charts6-dev should be replaced by qt6-chart-dev, and the elog need to be installed manually (or can be skipped)
`sudo apt install qt6-base-dev qt6-chart-dev libcurl4-openssl-dev`
I tested with a Raspberry Pi 5 with 8 GB + A4818 optical-USB adaptor. it works.
`sudo apt install qt6-base-dev libcurl4-openssl-dev libqt6charts6-dev`
# Compile
## in case the *.pro not exist or modified
use `qmake6 -project ` to generate the *.pro
in the *.pro, add
- ` QT += core widgets charts printsupport`
- ` LIBS += -lCAENDigitizer -lcurl`
` QT += core widgets charts`
## if *.pro exist
` LIBS += -lCAENDigitizer -lcurl`
then run ` qmake6 *.pro` it will generate Makefile
then ` make`
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.
# 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
```
# Known Issues
* If accessing the database takes too long, recommend to disable the database.
* Pile up rate is not accurate for very high input rate ( > 60 kHz ).
* 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.
* 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 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
* EventBuilder will crash when trigger rate of the data is very high.
then ` make`

View File

@ -27,16 +27,16 @@ class Reg{
Reg(){
name = "";
address = 0;
rwType = RW::ReadWrite;
type = RW::ReadWrite;
group = 0;
maxBit = 0;
partialStep = 0; //for time parameter, partial step * tick2ns = full step
partialStep = 0;
comboList.clear();
}
Reg(std::string name, uint32_t address, RW type = RW::ReadWrite, bool group = false, unsigned int max = 0, int pStep = 0){
this->name = name;
this->address = address;
this->rwType = type;
this->type = type;
this->group = group;
this->maxBit = max;
this->partialStep = pStep;
@ -46,7 +46,7 @@ class Reg{
Reg(std::string name, uint32_t address, RW type = RW::ReadWrite, bool group = false, std::vector<std::pair<std::string, unsigned int>> list = {}){
this->name = name;
this->address = address;
this->rwType = type;
this->type = type;
this->group = group;
this->maxBit = 0;
this->partialStep = 0;
@ -60,23 +60,17 @@ class Reg{
std::string GetName() const {return name;}
const char * GetNameChar() const {return name.c_str();}
uint32_t GetAddress() const {return address; }
RW GetRWType() const {return rwType;}
RW GetType() const {return type;}
bool IsCoupled() const {return group;}
unsigned int GetMaxBit() const {return maxBit;}
int GetPartialStep() const {return partialStep;} /// step = partialStep * tick2ns, -1 : step = 1
int GetPartialStep() const {return partialStep;} /// step = partialStep * ch2ns, -1 : step = 1
void Print() const ;
std::vector<std::pair<std::string, unsigned int>> GetComboList() const {return comboList;}
uint32_t ActualAddress(int ch = -1){ //for QDC, ch is groupID
if( address == 0x8180 ) return (ch < 0 ? address : (address + 4*(ch/2))); // DPP::TriggerValidationMask_G
if( address < 0x8000 ){
if( group ) {
if( ch < 0 ) return address + 0x7000;
return address + ((ch % 2 == 0 ? ch : ch - 1) << 8) ;
}
return (ch < 0 ? (address + 0x7000) : (address + (ch << 8)) );
}
uint32_t ActualAddress(int ch = -1){
if( address == 0x8180 ) return (ch < 0 ? address : (address + 4*(ch/2)));
if( address < 0x8000 ) return (ch < 0 ? (address + 0x7000) : (address + (ch << 8)) );
if( address >= 0x8000 ) return address;
return 0;
}
@ -90,7 +84,7 @@ class Reg{
std::string name;
uint32_t address; /// This is the table of register, the actual address should call ActualAddress();
RW rwType; /// read/write = 0; read = 1; write = 2
RW type; /// read/write = 0; read = 1; write = 2
bool group;
unsigned int maxBit ;
int partialStep;
@ -100,14 +94,14 @@ class Reg{
inline void Reg::Print() const{
printf(" Name: %s\n", name.c_str());
printf(" Re.Address: 0x%04X\n", address);
printf(" Type: %s\n", rwType == RW::ReadWrite ? "Read/Write" : (rwType == RW::ReadONLY ? "Read-Only" : "Write-Only") );
printf(" Type: %s\n", type == RW::ReadWrite ? "Read/Write" : (type == RW::ReadONLY ? "Read-Only" : "Write-Only") );
printf(" Group: %s\n", group ? "True" : "False");
printf(" Max Value : 0x%X = %d \n", maxBit, maxBit);
}
inline unsigned short Reg::Index (unsigned short ch){ //for QDC, ch = group
inline unsigned short Reg::Index (unsigned short ch){
unsigned short index;
if( address == 0x8180){ //DPP::TriggerValidationMask_G
if( address == 0x8180){
index = ((address + 4*(ch/2)) & 0x0FFF) / 4;
}else if( address < 0x8000){
index = (address + (ch << 8)) / 4;
@ -171,7 +165,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 ChannelEnableMask ("ChannelEnableMask" , 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,24 +193,19 @@ 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 {
namespace Bit_BoardConfig{
/// -------------------- shared with PHA, PSD, and QDC
const std::pair<unsigned short, unsigned short> AnalogProbe1 = {2, 12} ;
const std::pair<unsigned short, unsigned short> RecordTrace = {1, 16} ;
/// -------------------- shared with PHA and PSD
const std::pair<unsigned short, unsigned short> EnableAutoDataFlush = {1, 0} ; /// length, smallest pos
const std::pair<unsigned short, unsigned short> DecimateTrace = {1, 1} ;
const std::pair<unsigned short, unsigned short> TrigPropagation = {1, 2} ;
const std::pair<unsigned short, unsigned short> DualTrace = {1, 11} ;
const std::pair<unsigned short, unsigned short> EnableExtra2 = {1, 17} ;
/// -------------------- PHA only
const std::pair<unsigned short, unsigned short> DecimateTrace = {1, 1} ;
const std::pair<unsigned short, unsigned short> AnalogProbe1 = {2, 12} ;
const std::pair<unsigned short, unsigned short> AnalogProbe2 = {2, 14} ;
const std::pair<unsigned short, unsigned short> RecordTrace = {1, 16} ;
const std::pair<unsigned short, unsigned short> EnableExtra2 = {1, 17} ;
const std::pair<unsigned short, unsigned short> DigiProbel1_PHA = {4, 20} ;
const std::pair<unsigned short, unsigned short> DigiProbel2_PHA = {3, 26} ;
@ -245,7 +234,9 @@ namespace DPP {
const std::vector<std::pair<std::string, unsigned int>> ListDigiProbe2_PHA = {{"Trigger", 0}};
///------------------------ PSD only
///--------------------------
const std::pair<unsigned short, unsigned short> AnaProbe_PSD = {3, 11} ;
const std::pair<unsigned short, unsigned short> DigiProbel1_PSD = {3, 23} ;
const std::pair<unsigned short, unsigned short> DigiProbel2_PSD = {3, 26} ;
const std::pair<unsigned short, unsigned short> DisableDigiTrace_PSD = {1, 31} ;
@ -272,16 +263,6 @@ namespace DPP {
{"Baseline Freeze", 6},
{"Trigger", 7}};
/// -------------------- QDC only
const std::pair<unsigned short, unsigned short> ExtTriggerMode_QDC = {2, 20} ;
const std::vector<std::pair<std::string, unsigned int>> ListExtTriggerMode_QDC = {{"Trigger", 0},
{"Veto", 1},
{"Anti-Veto", 2}};
const std::vector<std::pair<std::string, unsigned int>> ListAnaProbe_QDC = {{"Input", 0},
{"Smoothed Input", 1},
{"Baseline", 2}};
}
namespace Bit_DPPAlgorithmControl_PHA {
@ -314,7 +295,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 = {{"Normal", 0},
const std::vector<std::pair<std::string, unsigned int>> ListTrigMode = {{"Independent", 0},
{"Coincident", 1},
{"Anti-Coincident", 3}};
@ -381,7 +362,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 = {{"Normal", 0},
const std::vector<std::pair<std::string, unsigned int>> ListTrigMode = {{"Independent", 0},
{"Coincident ", 1},
{"Anti-Coincident", 3}};
@ -390,25 +371,20 @@ namespace DPP {
{"64 samples", 2},
{"256 samples", 3},
{"1024 samples", 4}};
}
namespace Bit_DPPAlgorithmControl_QDC {
}
namespace Bit_AcquistionControl {
const std::pair<unsigned short, unsigned short> StartStopMode = {2, 0} ;
const std::pair<unsigned short, unsigned short> ACQStartArm = {1, 2} ;
const std::pair<unsigned short, unsigned short> TrigCountMode_QDC = {1, 3} ;
const std::pair<unsigned short, unsigned short> PLLRef = {1, 6} ;
const std::pair<unsigned short, unsigned short> LVDSBusyEnable = {1, 8} ;
const std::pair<unsigned short, unsigned short> LVDSVetoEnable = {1, 9} ;
const std::pair<unsigned short, unsigned short> LVDSRunInMode = {1, 11} ;
const std::pair<unsigned short, unsigned short> VetoTRGOut = {1, 12} ;
const std::vector<std::pair<std::string, unsigned int>> ListStartStopMode = {{"SW controlled", 0},
{"S-IN/GPI controlled", 1},
{"1st TRG-IN", 2},
{"1st Trigger", 2},
{"LVDS controlled", 3}};
const std::vector<std::pair<std::string, unsigned int>> ListACQStartArm = {{"ACQ STOP", 0},
@ -416,9 +392,6 @@ namespace DPP {
const std::vector<std::pair<std::string, unsigned int>> ListPLLRef = {{"Internal 50 MHz", 0},
{"Ext. CLK-IN", 1}};
const std::vector<std::pair<std::string, unsigned int>> ListTrigCountMode_QDC = {{"Comb. ch", 0},
{"Comb. ch + TRG-IN + SW", 1}};
}
namespace Bit_AcqStatus {
@ -479,8 +452,8 @@ namespace DPP {
const std::vector<std::pair<std::string, unsigned int>> ListLEMOLevel = {{"NIM I/O", 0},
{"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>> ListTRGINMezzanine = {{"Pocessed by Motherboard", 0},
{"Whole duration of TR-IN", 1}};
const std::vector<std::pair<std::string, unsigned int>> ListTRGIMezzanine = {{"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]
@ -508,7 +481,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, 0x1FF, -1); /// R/W
const Reg NumberEventsPerAggregate_G ("NumberEventsPerAggregate_G" , 0x1034, RW::ReadWrite, true, 0x3FF, -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
@ -542,10 +515,10 @@ namespace DPP {
const Reg FrontPanelTRGOUTEnableMask ("FrontPanelTRGOUTEnableMask" , 0x8110, 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 ChannelEnableMask ("ChannelEnableMask" , 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, 0xFFF, -1); /// R/W
const Reg VoltageLevelModeConfig ("VoltageLevelModeConfig" , 0x8138, RW::ReadWrite, false, {}); /// 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},
@ -600,9 +573,6 @@ 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
@ -636,7 +606,6 @@ namespace DPP {
const std::pair<unsigned short, unsigned short> TriggerCounterFlag = {2, 16} ;
const std::pair<unsigned short, unsigned short> ActivebaselineCalulation = {1, 18} ;
const std::pair<unsigned short, unsigned short> TagCorrelatedEvents = {1, 19} ;
const std::pair<unsigned short, unsigned short> ChannelProbe = {4, 20} ;
const std::pair<unsigned short, unsigned short> EnableActiveBaselineRestoration = {1, 29} ;
const std::vector<std::pair<std::string, unsigned int>> ListLocalShapeTrigMode = {{"Disabled", 0},
@ -646,8 +615,8 @@ namespace DPP {
{"OR", 7}};
const std::vector<std::pair<std::string, unsigned int>> ListLocalTrigValidMode = {{"Disabled", 0},
{"Crossed Trigger", 4},
{"Both from TRG_VAL", 5},
{"Crossed", 4},
{"Equal", 5},
{"AND", 6},
{"OR", 7}};
@ -665,19 +634,6 @@ namespace DPP {
{"128", 1},
{"8192", 2}};
const std::vector<std::pair<std::string, unsigned int>> ListChannelProbe = {{"Acq Armed", 1},
{"Self-Trig", 2},
{"Pile-Up", 3},
{"Pile-Up / Self-Trig", 4},
{"Veto", 5},
{"Coincident", 6},
{"Trig Valid.", 7},
{"Trig Valid. Acq Windown", 8},
{"Anti-coin. Event", 9},
{"Discard no coin. Event", 10},
{"Valid Event", 11},
{"Not Valid Event", 12}};
}
}
@ -697,7 +653,7 @@ namespace DPP {
const Reg ThresholdForPSDCut ("ThresholdForPSDCut" , 0x1078, RW::ReadWrite, false, 0x3FF, -1); /// R/W
const Reg PurGapThreshold ("PurGapThreshold" , 0x107C, RW::ReadWrite, false, 0xFFF, -1); /// R/W
const Reg DPPAlgorithmControl2_G ("DPPAlgorithmControl2_G" , 0x1084, RW::ReadWrite, true, {}); /// R/W
const Reg EarlyBaselineFreeze ("EarlyBaselineFreeze" , 0x10D8, RW::ReadWrite, false, 0x3FF, 4); /// R/W
const Reg EarlyBaselineFreeze ("EarlyBaselineFreeze" , 0x10D8, RW::ReadWrite, true, 0x3FF, 4); /// R/W
namespace Bit_CFDSetting {
const std::pair<unsigned short, unsigned short> CFDDealy = {8, 0} ;
@ -722,7 +678,6 @@ namespace DPP {
const std::pair<unsigned short, unsigned short> SmoothedChargeIntegration = {5, 11} ;
const std::pair<unsigned short, unsigned short> TriggerCounterFlag = {2, 16} ;
const std::pair<unsigned short, unsigned short> VetoSource = {2, 18} ;
const std::pair<unsigned short, unsigned short> ChannelProbe = {4, 20} ;
const std::pair<unsigned short, unsigned short> MarkSaturation = {1, 24} ;
const std::pair<unsigned short, unsigned short> AdditionLocalTrigValid = {2, 25} ;
const std::pair<unsigned short, unsigned short> VetoMode = {1, 27} ;
@ -735,8 +690,8 @@ namespace DPP {
{"OR", 7}};
const std::vector<std::pair<std::string, unsigned int>> ListLocalTrigValidMode = {{"Disabled", 0},
{"Crossed Trigger", 4},
{"Both from TRG_VAL", 5},
{"Crossed", 4},
{"Equal", 5},
{"AND", 6},
{"OR", 7}};
@ -757,19 +712,6 @@ namespace DPP {
{"Common (Global Trig. Mask)", 1},
{"Difference (Trig. Mask)", 2},
{"Negative Saturation", 3}};
const std::vector<std::pair<std::string, unsigned int>> ListChannelProbe = {{"OverThreshold", 1},
{"Self-Trig", 2},
{"Pile-Up", 3},
{"Pile-Up / Self-Trig", 4},
{"Veto", 5},
{"Coincident", 6},
{"Trig Valid.", 7},
{"Trig Valid. Acq Windown", 8},
{"Neutron Pulse", 9},
{"Gamma Pulse", 10},
{"Neutron Pulse (gate end)", 11},
{"Gamma Pulse (gate end)", 12}};
const std::vector<std::pair<std::string, unsigned int>> ListTrigCounter = {{"1024", 0},
{"128", 1},
@ -787,88 +729,17 @@ namespace DPP {
}
namespace QDC { // Register already grouped in channel. and there no control for indiviual channel except the Fine DC offset and threshold, so it is like no group
const Reg GateWidth ("GateWidth" , 0x1030, RW::ReadWrite, false, 0xFFF, 1); /// R/W
const Reg GateOffset ("GateOfset" , 0x1034, RW::ReadWrite, false, 0xFF, 1); /// R/W
const Reg FixedBaseline ("FixedBaseline" , 0x1038, RW::ReadWrite, false, 0xFFF, -1); /// R/W
const Reg PreTrigger ("PreTrigger" , 0x103C, RW::ReadWrite, false, 0xFF, 1); /// R/W
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 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
const Reg SubChannelMask ("SubChannel Mask" , 0x10A8, RW::ReadWrite, false, 0xFF, -1); /// R/W
const Reg DCOffset_LowCh ("DC offset for low ch." , 0x10C0, RW::ReadWrite, false, 0xFFFFFFFF, -1); /// R/W
const Reg DCOffset_HighCh ("DC offset for high ch." , 0x10C4, RW::ReadWrite, false, 0xFFFFFFFF, -1); /// R/W
const Reg TriggerThreshold_sub0 ("Trigger Threshold sub0" , 0x10D0, RW::ReadWrite, false, 0xFFF, -1); /// R/W
const Reg TriggerThreshold_sub1 ("Trigger Threshold sub1" , 0x10D4, RW::ReadWrite, false, 0xFFF, -1); /// R/W
const Reg TriggerThreshold_sub2 ("Trigger Threshold sub2" , 0x10D8, RW::ReadWrite, false, 0xFFF, -1); /// R/W
const Reg TriggerThreshold_sub3 ("Trigger Threshold sub3" , 0x10DC, RW::ReadWrite, false, 0xFFF, -1); /// R/W
const Reg TriggerThreshold_sub4 ("Trigger Threshold sub4" , 0x10E0, RW::ReadWrite, false, 0xFFF, -1); /// R/W
const Reg TriggerThreshold_sub5 ("Trigger Threshold sub5" , 0x10E4, RW::ReadWrite, false, 0xFFF, -1); /// R/W
const Reg TriggerThreshold_sub6 ("Trigger Threshold sub6" , 0x10E8, RW::ReadWrite, false, 0xFFF, -1); /// R/W
const Reg TriggerThreshold_sub7 ("Trigger Threshold sub7" , 0x10EC, RW::ReadWrite, false, 0xFFF, -1); /// R/W
const Reg GroupEnableMask ("Group Enable Mask" , 0x8120, RW::ReadWrite, false, 0xFF, -1); /// R/W
const Reg NumberEventsPerAggregate ("Number of Events per Aggregate", 0x8020, RW::ReadWrite, false, 0x3FF, -1); /// R/W
const Reg RecordLength_W ("Record Length_W" , 0x8024, RW::WriteONLY, false, 0x1FFF, 8); /// R/W
const Reg RecordLength_R ("Record Length_R" , 0x1024, RW::ReadONLY, false, 0x1FFF, 8); /// R/W
namespace Bit_DPPAlgorithmControl {
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> ChargePedestal = {1, 8};
const std::pair<unsigned short, unsigned short> InputSmoothingFactor = {3, 12};
const std::pair<unsigned short, unsigned short> Polarity = {1, 16};
const std::pair<unsigned short, unsigned short> TriggerMode = {2, 18};
const std::pair<unsigned short, unsigned short> BaselineAvg = {3, 20};
const std::pair<unsigned short, unsigned short> DisableSelfTrigger = {1, 24};
const std::pair<unsigned short, unsigned short> DisableTriggerHysteresis = {1, 30};
const std::vector<std::pair<std::string, unsigned int>> ListChargeSensitivity = {{"0.16 pC", 0},
{"0.32 pC", 1},
{"0.64 pC", 2},
{"1.28 pC", 3},
{"2.56 pC", 4},
{"5.12 pC", 5},
{"10.24 pC", 6},
{"20.48 pC", 7}};
const std::vector<std::pair<std::string, unsigned int>> ListTestPulseRate = {{"1 kHz", 0},
{"10 kHz", 1},
{"100 kHz", 2},
{"1 MHz", 3}};
const std::vector<std::pair<std::string, unsigned int>> ListInputSmoothingFactor = {{"Disabled", 0},
{"2 samples", 1},
{"4 samples", 2},
{"8 samples", 3},
{"16 samples", 4},
{"32 samples", 5},
{"64 samples", 6}};
const std::vector<std::pair<std::string, unsigned int>> ListPolarity = {{"Positive", 0},
{"Negative", 1}};
const std::vector<std::pair<std::string, unsigned int>> ListTrigMode = {{"Self-Trigger", 0},
{"Coupled OR", 1}};
const std::vector<std::pair<std::string, unsigned int>> ListBaselineAvg = {{"Fixed", 0},
{"4 samples", 1},
{"16 samples", 2},
{"64 samples", 3}};
}
namespace QDC {
const Reg GateWidth ("GateWidth" , 0x1030, RW::ReadWrite, false, 0xFFF, 4); /// R/W
const Reg GateOffset ("GateOfset" , 0x1034, RW::ReadWrite, false, 0xFF, 4); /// R/W
const Reg FixedBaseline ("FixedBaseline" , 0x1038, RW::ReadWrite, false, 0xFFF, 4); /// R/W
const Reg Pretrigger ("PreTrigger" , 0x103C, RW::ReadWrite, false, 0xFF, 4); /// R/W
const Reg DPPAlgorithmControl ("DPPAlgorithmControl" , 0x1040, RW::ReadWrite, false, {}); /// R/W
}
} // end of DPP namepace Register
const std::vector<Reg> RegisterChannelList_PHA = {
const std::vector<Reg> RegisterPHAList = {
DPP::RecordLength_G ,
DPP::InputDynamicRange ,
DPP::NumberEventsPerAggregate_G ,
@ -898,7 +769,7 @@ const std::vector<Reg> RegisterChannelList_PHA = {
DPP::TriggerValidationMask_G
};
const std::vector<Reg> RegisterChannelList_PSD = {
const std::vector<Reg> RegisterPSDList = {
DPP::RecordLength_G ,
DPP::InputDynamicRange ,
DPP::NumberEventsPerAggregate_G ,
@ -928,34 +799,14 @@ const std::vector<Reg> RegisterChannelList_PSD = {
DPP::TriggerValidationMask_G
};
const std::vector<Reg> RegisterChannelList_QDC = {
// DPP::QDC::RecordLength,
DPP::QDC::GateWidth,
DPP::QDC::GateOffset,
DPP::QDC::FixedBaseline,
DPP::QDC::PreTrigger,
DPP::QDC::DPPAlgorithmControl,
DPP::QDC::TriggerHoldOffWidth,
DPP::QDC::TRGOUTWidth,
DPP::QDC::OverThresholdWidth,
DPP::QDC::GroupStatus_R,
DPP::QDC::AMCFirmwareRevision_R,
DPP::QDC::DCOffset,
DPP::QDC::SubChannelMask,
DPP::QDC::DCOffset_LowCh,
DPP::QDC::DCOffset_HighCh,
DPP::QDC::TriggerThreshold_sub0,
DPP::QDC::TriggerThreshold_sub1,
DPP::QDC::TriggerThreshold_sub2,
DPP::QDC::TriggerThreshold_sub3,
DPP::QDC::TriggerThreshold_sub4,
DPP::QDC::TriggerThreshold_sub5,
DPP::QDC::TriggerThreshold_sub6,
DPP::QDC::TriggerThreshold_sub7
const std::vector<Reg> RegisterQDCList = { //TODO
};
/// Only Board Setting
const std::vector<Reg> RegisterBoardList_PHAPSD = {
const std::vector<Reg> RegisterDPPList = {
DPP::BoardConfiguration ,
DPP::AggregateOrganization ,
DPP::ADCCalibration_W ,
@ -967,7 +818,7 @@ const std::vector<Reg> RegisterBoardList_PHAPSD = {
DPP::FrontPanelTRGOUTEnableMask ,
DPP::LVDSIOData ,
DPP::FrontPanelIOControl ,
DPP::RegChannelEnableMask ,
DPP::ChannelEnableMask ,
DPP::ROCFPGAFirmwareRevision_R ,
DPP::EventStored_R ,
DPP::VoltageLevelModeConfig ,
@ -1022,73 +873,4 @@ const std::vector<Reg> RegisterBoardList_PHAPSD = {
};
const std::vector<Reg> RegisterBoardList_QDC = {
DPP::BoardConfiguration ,
DPP::AggregateOrganization,
DPP::QDC::NumberEventsPerAggregate,
DPP::QDC::RecordLength_W,
DPP::QDC::RecordLength_R,
DPP::DecimationFactor,
DPP::AcquisitionControl,
DPP::AcquisitionStatus_R,
DPP::SoftwareTrigger_W,
DPP::GlobalTriggerMask,
DPP::FrontPanelTRGOUTEnableMask,
DPP::LVDSIOData,
DPP::FrontPanelIOControl,
DPP::QDC::GroupEnableMask,
DPP::ROCFPGAFirmwareRevision_R,
DPP::VoltageLevelModeConfig,
DPP::SoftwareClockSync_W,
DPP::BoardInfo_R,
DPP::AnalogMonitorMode,
DPP::EventSize_R,
DPP::TimeBombDowncounter_R,
DPP::FanSpeedControl,
DPP::RunStartStopDelay,
DPP::BoardFailureStatus_R,
DPP::DisableExternalTrigger,
DPP::FrontPanelLVDSIONewFeatures,
DPP::BufferOccupancyGain,
DPP::ExtendedVetoDelay,
DPP::ReadoutControl,
DPP::ReadoutStatus_R,
DPP::BoardID,
DPP::MCSTBaseAddressAndControl,
DPP::RelocationAddress,
DPP::InterruptStatusID,
DPP::InterruptEventNumber,
DPP::MaxAggregatePerBlockTransfer,
DPP::Scratch ,
DPP::SoftwareReset_W ,
DPP::SoftwareClear_W ,
DPP::ConfigurationReload_W ,
DPP::ROMChecksum_R ,
DPP::ROMChecksumByte2_R ,
DPP::ROMChecksumByte1_R ,
DPP::ROMChecksumByte0_R ,
DPP::ROMConstantByte2_R ,
DPP::ROMConstantByte1_R ,
DPP::ROMConstantByte0_R ,
DPP::ROM_C_Code_R ,
DPP::ROM_R_Code_R ,
DPP::ROM_IEEE_OUI_Byte2_R ,
DPP::ROM_IEEE_OUI_Byte1_R ,
DPP::ROM_IEEE_OUI_Byte0_R ,
DPP::ROM_BoardVersion_R ,
DPP::ROM_BoardFromFactor_R ,
DPP::ROM_BoardIDByte1_R ,
DPP::ROM_BoardIDByte0_R ,
DPP::ROM_PCB_rev_Byte3_R ,
DPP::ROM_PCB_rev_Byte2_R ,
DPP::ROM_PCB_rev_Byte1_R ,
DPP::ROM_PCB_rev_Byte0_R ,
DPP::ROM_FlashType_R ,
DPP::ROM_BoardSerialNumByte1_R ,
DPP::ROM_BoardSerialNumByte0_R ,
DPP::ROM_VCXO_Type_R
};
#endif

919
Scope.cpp

File diff suppressed because it is too large Load Diff

65
Scope.h
View File

@ -12,7 +12,6 @@
#include <QComboBox>
#include <QGridLayout>
#include <QGroupBox>
#include <QTimer>
#include <QLineSeries>
#include <QRubberBand>
#include <QMouseEvent>
@ -23,8 +22,6 @@
#include "CustomThreads.h"
#include "CustomWidgets.h"
class ScopeWorker; //Forward declaration
//^====================================================
//^====================================================
class Scope : public QMainWindow{
@ -35,13 +32,11 @@ public:
~Scope();
void closeEvent(QCloseEvent * event){
if(isACQStarted) StopScope();
StopScope();
emit CloseWindow();
event->accept();
}
QVector<QPointF> TrapezoidFilter(QVector<QPointF> data, int baseLineEndS, int riseTimeS, int flatTopS, float decayTime_ns );
public slots:
void StartScope();
void StopScope();
@ -54,6 +49,7 @@ signals:
void CloseWindow();
void SendLogMsg(const QString &msg);
void TellACQOnOff(const bool onOff);
void UpdateScaler();
void UpdateOtherPanels();
private:
@ -63,39 +59,29 @@ private:
void SetUpSpinBox(RSpinBox * &sb, QString str, int row, int col, const Reg para);
void CleanUpSettingsGroupBox();
void SetUpPanel_PHA();
void SetUpPanel_PSD();
void SetUpPanel_QDC();
void SetUpPHAPanel();
void SetUpPSDPanel();
void EnableControl(bool enable);
void UpdateComobox(RComboBox * &cb, const Reg para);
void UpdateSpinBox(RSpinBox * &sb, const Reg para);
void UpdatePanel_PHA();
void UpdatePanel_PSD();
void UpdatePanel_QDC();
void NullThePointers();
void UpdatePHAPanel();
void UpdatePSDPanel();
Digitizer ** digi;
unsigned short nDigi;
unsigned short ID; // the id of digi, index of cbScopeDigi
bool isACQStarted;
int tick2ns;
int factor; // whether dual trace or not
int AggPerRead[MaxNDigitizer];
int ch2ns;
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;
bool enableSignalSlot;
RChart * plot;
RChartView * plotView;
QLineSeries * dataTrace[MaxNumberOfTrace]; // 2 analog, 2 digi for PHA, PSD, 1 analog, 4 digi for QDC
Trace * plot;
TraceView * plotView;
QLineSeries * dataTrace[MaxNumberOfTrace]; // 2 analog, 2 digi
RComboBox * cbScopeDigi;
RComboBox * cbScopeCh;
@ -109,9 +95,6 @@ private:
QGroupBox * settingGroup;
QGridLayout * settingLayout;
QCheckBox * chkSoleRun;
QPushButton * runStatus;
/// common to PSD and PHA
RSpinBox * sbReordLength;
RSpinBox * sbPreTrigger;
@ -143,34 +126,8 @@ private:
RSpinBox * sbLongGate;
RSpinBox * sbGateOffset;
/// QDC
//sbShortGate -> GateWidth
//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

@ -1,473 +0,0 @@
#include "SingleSpectra.h"
#include <QValueAxis>
#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->settingPath = rawDataPath + "/HistogramSettings.txt";
maxFillTimeinMilliSec = SingleHistogramFillingTime;
isSignalSlotActive = true;
setWindowTitle("Single Histograms");
//====== 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);
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();
cbCh->addItem("All Ch", digi[index]->GetNumInputCh() );
for( int i = 0; i < digi[index]->GetNumInputCh(); i++) cbCh->addItem("ch-" + QString::number( i ), i);
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);
// }
// }
cbCh->setCurrentIndex(oldChComboBoxindex[index]);
ChangeHistView();
});
cbCh = new RComboBox(this);
cbCh->addItem("All Ch", digi[0]->GetNumInputCh());
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);
QPushButton * bnClearHist = new QPushButton("Clear All Hist.", this);
ctrlLayout->addWidget(bnClearHist, 0, 4, 1, 2);
connect(bnClearHist, &QPushButton::clicked, this, [=](){
for( unsigned int i = 0; i < nDigi; i++){
for( int j = 0; j < digi[i]->GetNumInputCh(); j++){
if( hist[i][j] ) hist[i][j]->Clear();
}
if( hist2D[i] ) hist2D[i]->Clear();
}
});
chkIsFillHistogram = new QCheckBox("Fill Histograms", this);
ctrlLayout->addWidget(chkIsFillHistogram, 0, 6, 1, 2);
chkIsFillHistogram->setChecked(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);
}
{//^========================
for( unsigned int i = 0; i < nDigi; i++ ) {
hist2DVisibility[i] = false;
for( int j = 0; j < digi[i]->GetNumInputCh() ; j++ ) {
histVisibility[i][j] = false;
}
}
histBox = new QGroupBox("Histgrams", this);
layout->addWidget(histBox);
histLayout = new QGridLayout(histBox);
histBox->setLayout(histLayout);
double eMax = 5000;
double eMin = 0;
double nBin = 200;
for( unsigned int i = 0; i < MaxNDigitizer; i++){
if( i >= nDigi ) continue;
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;
}
}
hist2D[i] = new Histogram2D("Digi-" + QString::number(digi[i]->GetSerialNumber()), "Channel", "Raw Energy [ch]", digi[i]->GetNumInputCh(), 0, digi[i]->GetNumInputCh(), nBin, eMin, eMax);
hist2D[i]->SetChannelMap(true, digi[i]->GetNumInputCh() < 20 ? 1 : 4);
hist2D[i]->Rebin(digi[i]->GetNumInputCh(), -0.5, digi[i]->GetNumInputCh()+0.5, nBin, eMin, eMax);
}
LoadSetting();
histLayout->addWidget(hist2D[0], 0, 0);
hist2DVisibility[0] = true;
}
//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++ ){
for( int ch = 0; ch < digi[i]->GetNumInputCh(); ch++){
delete hist[i][ch];
}
delete hist2D[i];
}
}
void SingleSpectra::ClearInternalDataCount(){
DebugPrint("%s", "SingleSpectra");
for( unsigned int i = 0; i < nDigi; i++){
for( int ch = 0; ch < MaxRegChannel ; ch++) {
lastFilledIndex[i][ch] = -1;
}
}
}
void SingleSpectra::ChangeHistView(){
DebugPrint("%s", "SingleSpectra");
if( !isSignalSlotActive ) return;
int bd = cbDigi->currentIndex();
int ch = cbCh->currentData().toInt();
//printf("bd : %d, ch : %d \n", bd, ch);
// Remove oldCh
int oldCh = oldChComboBoxindex[oldBd] == 0 ? digi[oldBd]->GetNumInputCh() : oldChComboBoxindex[oldBd] - 1;
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;
}
// Add ch
if( ch >=0 && ch < digi[bd]->GetNumInputCh()) {
histLayout->addWidget(hist[bd][ch], 0, 0);
histVisibility[bd][ch] = true;
hist[bd][ch]->UpdatePlot();
}
if( ch == digi[bd]->GetNumInputCh() ){
histLayout->addWidget(hist2D[bd], 0, 0);
hist2DVisibility[bd] = true;
hist2D[bd]->UpdatePlot();
}
oldBd = bd;
oldChComboBoxindex[bd] = cbCh->currentIndex();
}
void SingleSpectra::FillHistograms(){
// printf("%s | %d %d \n", __func__, chkIsFillHistogram->checkState(), isFillingHistograms);
if( this->isVisible() == false ) return;
if( chkIsFillHistogram->checkState() == Qt::Unchecked ) return;
if( isFillingHistograms) return;
isFillingHistograms = true;
// timespec t0, t1;
timespec ta, tb;
printf("####################### SingleSpectra::%s\n", __func__);
// qDebug() << __func__ << "| thread:" << QThread::currentThreadId();
clock_gettime(CLOCK_REALTIME, &ta);
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;
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() ) lastFilledIndex[ID][ch] = temp1 - digi[ID]->GetData()->GetDataSize() ;
}
}
int nSize = digiChList.size();
if( nSize == 0 ) {
isFillingHistograms = false;
return;
}
// 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;
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;
}
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(settingPath );
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();
}
}
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(settingPath);
if( file.open(QIODevice::Text | QIODevice::ReadOnly) ){
QTextStream in(&file);
QString line = in.readLine();
int digiSN = 0;
int digiID = -1;
while ( !line.isNull() ){
if( line.contains("##========== ") ) break;
if( line.contains("//") ) continue;
if( line.contains("======= ") ){
digiSN = line.mid(7).toInt();
digiID = -1;
for( unsigned int i = 0; i < nDigi; i++){
if( digiSN == digi[i]->GetSerialNumber() ) {
digiID = i;
break;
}
}
line = in.readLine();
continue;
}
if( digiID >= 0 ){
QStringList list = line.split(QRegularExpression("\\s+"));
list.removeAll("");
// if( list.count() != 4 ) {
// line = in.readLine();
// continue;
// }
QVector<float> data;
for( int i = 0; i < list.count(); i++){
data.push_back(list[i].toFloat());
}
if( 0 <= data[0] && data[0] < digi[digiID]->GetNumInputCh() ){
hist[digiID][int(data[0])]->Rebin(data[1], data[2], data[3]);
}
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]);
}
}
line = in.readLine();
}
}else{
printf("%s|cannot open HistogramSettings.txt\n", __func__);
}
}
QVector<int> SingleSpectra::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;
}

View File

@ -1,124 +0,0 @@
#ifndef SINGLE_SPECTR_H
#define SINGLE_SPECTR_H
#include <QMainWindow>
#include <QChart>
#include <QChartView>
#include <QLabel>
#include <QPushButton>
#include <QCheckBox>
#include <QLineEdit>
#include <QGridLayout>
#include <QGroupBox>
#include <QVector>
#include <QRandomGenerator>
#include "macro.h"
#include "ClassDigitizer.h"
#include "CustomThreads.h"
#include "CustomWidgets.h"
#include "Histogram1D.h"
#include "Histogram2D.h"
class HistWorker; //Forward decalration
//^====================================================
//^====================================================
class SingleSpectra : public QMainWindow{
Q_OBJECT
public:
SingleSpectra(Digitizer ** digi, unsigned int nDigi, QString rawDataPath, QMainWindow * parent = nullptr);
~SingleSpectra();
void ClearInternalDataCount();
// void SetFillHistograms(bool onOff) { fillHistograms = onOff;}
// bool IsFillHistograms() const {return fillHistograms;}
void LoadSetting();
void SaveSetting();
void SetMaxFillTime(unsigned short milliSec) { maxFillTimeinMilliSec = milliSec;}
unsigned short GetMaxFillTime() const {return maxFillTimeinMilliSec;};
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];
QCheckBox * chkIsFillHistogram;
RComboBox * cbDivision;
RComboBox * cbDigi;
RComboBox * cbCh;
QGroupBox * histBox;
QGridLayout * histLayout;
int oldBd;
int oldChComboBoxindex[MaxNDigitizer]; // the ID of hist for display
QString settingPath;
unsigned short maxFillTimeinMilliSec;
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

@ -1,252 +0,0 @@
#include "Analyser.h"
#include "CustomWidgets.h"
#include <QRandomGenerator>
#include <random>
Analyzer::Analyzer(Digitizer ** digi, unsigned int nDigi, QMainWindow * parent ): QMainWindow(parent), dataList(NULL){
this->digi = digi;
this->nDigi = nDigi;
setWindowTitle("Online Analyzer");
setGeometry(0, 0, 1000, 800);
influx = nullptr;
dataBaseIP = "";
dataBaseName = "";
dataBaseToken = "";
dataList = new Data*[nDigi];
typeList.clear();
snList.clear();
for( unsigned int k = 0; k < nDigi; k ++) {
dataList[k] = digi[k]->GetData();
typeList.push_back(digi[k]->GetDPPType());
snList.push_back(digi[k]->GetSerialNumber());
}
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);
QWidget * layoutWidget = new QWidget(this);
setCentralWidget(layoutWidget);
layout = new QGridLayout(layoutWidget);
layoutWidget->setLayout(layout);
// 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;
}
double Analyzer::RandomGauss(double mean, double sigma){
// Box-Muller transform to generate normally distributed random numbers
double u1 = QRandomGenerator::global()->generateDouble();
double u2 = QRandomGenerator::global()->generateDouble();
double z0 = sqrt(-2.0 * log(u1)) * cos(2 * M_PI * u2);
// Apply mean and standard deviation
return mean + z0 * 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;
typeList.clear();
snList.clear();
dataList = new Data*[idList.size()];
for( size_t k = 0; k < idList.size(); k ++) {
dataList[k] = digi[idList[k]]->GetData();
typeList.push_back(digi[idList[k]]->GetDPPType());
snList.push_back(digi[idList[k]]->GetSerialNumber());
}
mb = new MultiBuilder(dataList, typeList, snList);
}
void Analyzer::BuildEvents(bool verbose){
// 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, 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());
}
}
//^####################################### below are open to customization
void Analyzer::SetUpCanvas(){
}
void Analyzer::UpdateHistograms(){
}
void Analyzer::ReplotHistograms(){
}

View File

@ -1,135 +0,0 @@
#ifndef ANALYZER_H
#define ANALYZER_H
#include <QMainWindow>
#include <QChart>
#include <QChartView>
#include <QLabel>
#include <QPushButton>
#include <QCheckBox>
#include <QLineEdit>
#include <QGridLayout>
#include <QGroupBox>
#include "macro.h"
#include "ClassDigitizer.h"
#include "CustomThreads.h"
#include "CustomWidgets.h"
#include "MultiBuilder.h"
#include "ClassInfluxDB.h"
#include "math.h"
/**************************************
This class is for, obviously, Online analysis.
It provides essential event building, histograms, and filling.
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{
Q_OBJECT
public:
Analyzer(Digitizer ** digi, unsigned int nDigi, QMainWindow * parent = nullptr);
virtual ~Analyzer();
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 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; }
InfluxDB * influx;
QString dataBaseIP;
QString dataBaseName;
QString dataBaseToken;
bool isWorking; // a flag to indicate the worker is working
Digitizer ** digi;
unsigned short nDigi;
Data ** dataList;
std::vector<int> typeList;
std::vector<int> snList;
double waitTimeinSec;
MultiBuilder * mb;
bool isBuildBackward;
int maxNumEventBuilt;
// TimingThread * buildTimerThread;
QThread * anaThread;
AnalyzerWorker * anaWorker;
QTimer * anaTimer;
};
//^================================================ 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

@ -1,673 +0,0 @@
#ifndef COINCIDENTANLAYZER_H
#define COINCIDENTANLAYZER_H
#include "Analyser.h"
#include "FSUDAQ.h"
//^===========================================
class CoincidentAnalyzer : public Analyzer{
Q_OBJECT
public:
CoincidentAnalyzer(Digitizer ** digi, unsigned int nDigi, QString rawDataPath, QMainWindow * parent = nullptr): Analyzer(digi, nDigi, parent){
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.
mb->SetTimeWindow(500);
allowSignalSlot = false;
SetUpCanvas();
}
~CoincidentAnalyzer(){
}
void SetUpCanvas();
public slots:
void UpdateHistograms();
void ReplotHistograms();
private:
bool allowSignalSlot;
QLineEdit * leInfluxIP;
QLineEdit * leDBName;
// declaie histograms
Histogram2D * h2D;
Histogram1D * h1;
Histogram1D * h1g;
Histogram1D * hMulti;
QCheckBox * chkRunAnalyzer;
RSpinBox * sbUpdateTime;
QCheckBox * chkBackWardBuilding;
RSpinBox * sbBackwardCount;
RSpinBox * sbBuildWindow;
// data source for the h2D
RComboBox * xDigi;
RComboBox * xCh;
RComboBox * yDigi;
RComboBox * yCh;
// data source for the h1
RComboBox * aDigi;
RComboBox * aCh;
QString rawDataPath;
void SaveSettings();
void LoadSettings();
};
inline void CoincidentAnalyzer::SetUpCanvas(){
setWindowTitle("Online Coincident Analyzer");
setGeometry(0, 0, 1600, 1000);
{//^====== 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, 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, rowID, 1);
sbUpdateTime = new RSpinBox(this, 1);
sbUpdateTime->setMinimum(0.1);
sbUpdateTime->setMaximum(5);
sbUpdateTime->setValue(1);
boxLayout->addWidget(sbUpdateTime, rowID, 2);
connect(sbUpdateTime, &RSpinBox::valueChanged, this, [=](){ sbUpdateTime->setStyleSheet("color : blue"); });
connect(sbUpdateTime, &RSpinBox::returnPressed, this, [=](){
sbUpdateTime->setStyleSheet("");
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, rowID, 0);
QLabel * lbBKWindow = new QLabel("Max No. Backward Event", this);
lbBKWindow->setAlignment(Qt::AlignRight | Qt::AlignCenter);
boxLayout->addWidget(lbBKWindow, rowID, 1);
sbBackwardCount = new RSpinBox(this, 0);
sbBackwardCount->setMinimum(1);
sbBackwardCount->setMaximum(9999);
sbBackwardCount->setValue(100);
boxLayout->addWidget(sbBackwardCount, rowID, 2);
chkBackWardBuilding->setChecked(false);
sbBackwardCount->setEnabled(false);
connect(chkBackWardBuilding, &QCheckBox::stateChanged, this, [=](int status){
SetBackwardBuild(status, sbBackwardCount->value());
sbBackwardCount->setEnabled(status);
SetBackwardBuild(true, sbBackwardCount->value());
});
connect(sbBackwardCount, &RSpinBox::valueChanged, this, [=](){
sbBackwardCount->setStyleSheet("color : blue;");
});
connect(sbBackwardCount, &RSpinBox::returnPressed, this, [=](){
sbBackwardCount->setStyleSheet("");
SetBackwardBuild(true, sbBackwardCount->value());
});
}
{
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, 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, rowID, 1);
QLabel * lbXCh = new QLabel("X-Ch", this);
lbXCh->setAlignment(Qt::AlignRight | Qt::AlignCenter);
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, rowID, 3);
rowID ++;
QLabel * lbYDigi = new QLabel("Y-Digi", this);
lbYDigi->setAlignment(Qt::AlignRight | Qt::AlignCenter);
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, rowID, 1);
QLabel * lbYCh = new QLabel("Y-Ch", this);
lbYCh->setAlignment(Qt::AlignRight | Qt::AlignCenter);
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, rowID, 3);
connect(xDigi, &RComboBox::currentIndexChanged, this, [=](){
allowSignalSlot = false;
xCh->clear();
for( int i = 0; i < digi[0]->GetNumInputCh(); i++) xCh->addItem("Ch-" + QString::number(i), i);
allowSignalSlot = true;
int bd = xDigi->currentData().toInt();
int ch = xCh->currentData().toInt();
h2D->SetXTitle("Digi-" + QString::number(digi[bd]->GetSerialNumber()) + ", Ch-" + QString::number(ch));
h2D->UpdatePlot();
});
connect(xCh, &RComboBox::currentIndexChanged, this, [=](){
if( !allowSignalSlot) return;
int bd = xDigi->currentData().toInt();
int ch = xCh->currentData().toInt();
h2D->SetXTitle("Digi-" + QString::number(digi[bd]->GetSerialNumber()) + ", Ch-" + QString::number(ch));
h2D->UpdatePlot();
});
connect(yDigi, &RComboBox::currentIndexChanged, this, [=](){
allowSignalSlot = false;
yCh->clear();
for( int i = 0; i < digi[0]->GetNumInputCh(); i++) yCh->addItem("Ch-" + QString::number(i), i);
allowSignalSlot = true;
int bd = yDigi->currentData().toInt();
int ch = yCh->currentData().toInt();
h2D->SetYTitle("Digi-" + QString::number(digi[bd]->GetSerialNumber()) + ", Ch-" + QString::number(ch));
h2D->UpdatePlot();
});
connect(yCh, &RComboBox::currentIndexChanged, this, [=](){
if( !allowSignalSlot) return;
int bd = yDigi->currentData().toInt();
int ch = yCh->currentData().toInt();
h2D->SetYTitle("Digi-" + QString::number(digi[bd]->GetSerialNumber()) + ", Ch-" + QString::number(ch));
h2D->UpdatePlot();
});
}
{
rowID ++;
QFrame *separator1 = new QFrame(box);
separator1->setFrameShape(QFrame::HLine);
separator1->setFrameShadow(QFrame::Sunken);
boxLayout->addWidget(separator1, rowID, 0, 1, 4);
rowID ++;
QLabel * lbaDigi = new QLabel("ID-Digi", this);
lbaDigi->setAlignment(Qt::AlignRight | Qt::AlignCenter);
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()), i);
}
boxLayout->addWidget(aDigi, rowID, 1);
QLabel * lbaCh = new QLabel("1D-Ch", this);
lbaCh->setAlignment(Qt::AlignRight | Qt::AlignCenter);
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, rowID, 3);
connect(aDigi, &RComboBox::currentIndexChanged, this, [=](){
allowSignalSlot = false;
aCh->clear();
for( int i = 0; i < digi[0]->GetNumInputCh(); i++) aCh->addItem("Ch-" + QString::number(i), i);
allowSignalSlot = true;
int bd = aDigi->currentData().toInt();
int ch = aCh->currentData().toInt();
h1->SetXTitle("Digi-" + QString::number(digi[bd]->GetSerialNumber()) + ", Ch-" + QString::number(ch));
h1->UpdatePlot();
h1g->SetXTitle("Digi-" + QString::number(digi[bd]->GetSerialNumber()) + ", Ch-" + QString::number(ch));
h1g->UpdatePlot();
});
connect(aCh, &RComboBox::currentIndexChanged, this, [=](){
if( !allowSignalSlot) return;
int bd = aDigi->currentData().toInt();
int ch = aCh->currentData().toInt();
h1->SetXTitle("Digi-" + QString::number(digi[bd]->GetSerialNumber()) + ", Ch-" + QString::number(ch));
h1->UpdatePlot();
h1g->SetXTitle("Digi-" + QString::number(digi[bd]->GetSerialNumber()) + ", Ch-" + QString::number(ch));
h1g->UpdatePlot();
});
}
{
rowID ++;
QFrame *separator2 = new QFrame(box);
separator2->setFrameShape(QFrame::HLine);
separator2->setFrameShadow(QFrame::Sunken);
boxLayout->addWidget(separator2, rowID, 0, 1, 4);
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();
h1->Clear();
h1g->Clear();
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", "", 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", 200, 0, 30000, 200, 0, 30000, this, rawDataPath);
//layout is inheriatge from Analyzer
layout->addWidget(h2D, 1, 0, 2, 1);
int bd = xDigi->currentData().toInt();
int ch = xCh->currentData().toInt();
h2D->SetXTitle("Digi-" + QString::number(digi[bd]->GetSerialNumber()) + ", Ch-" + QString::number(ch));
bd = yDigi->currentData().toInt();
ch = yCh->currentData().toInt();
h2D->SetYTitle("Digi-" + QString::number(digi[bd]->GetSerialNumber()) + ", Ch-" + QString::number(ch));
h2D->UpdatePlot();
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
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, 30000, this);
h1g->SetXTitle("Digi-" + QString::number(digi[bd]->GetSerialNumber()) + ", Ch-" + QString::number(ch));
h1g->UpdatePlot();
layout->addWidget(h1g, 2, 1);
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;
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 = mb->eventBuilt;
if( eventBuilt == 0 ) return;
//============ Get the cut list, if any
QList<QPolygonF> cutList = h2D->GetCutList();
const int nCut = cutList.count();
unsigned long long tMin[nCut] = {0xFFFFFFFFFFFFFFFF}, tMax[nCut] = {0};
unsigned int count[nCut]={0};
//============ Get the channel to plot
int a_bd = aDigi->currentData().toInt();
int a_ch = aCh->currentData().toInt();
int x_bd = xDigi->currentData().toInt();
int x_ch = xCh->currentData().toInt();
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 = 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];
hMulti->Fill((int) event.size());
if( event.size() == 0 ) return;
int aE = -1;
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_sn && event[k].ch == a_ch) {
h1->Fill(event[k].energy);
aE = event[k].energy;
}
if( event[k].sn == x_sn && event[k].ch == x_ch) {
xE = event[k].energy;
xT = event[k].timestamp;
}
if( event[k].sn == y_sn && event[k].ch == y_ch) yE = event[k].energy;
}
if( xE >= 0 && yE >= 0 ) h2D->Fill(xE, yE);
//check events inside any Graphical cut and extract the rate
for(int p = 0; p < cutList.count(); p++ ){
if( cutList[p].isEmpty() ) continue;
if( cutList[p].containsPoint(QPointF(xE, yE), Qt::OddEvenFill) && xE >= 0 && yE >= 0 ){
if( xT < tMin[p] ) tMin[p] = xT;
if( xT > tMax[p] ) tMax[p] = xT;
count[p] ++;
//printf(".... %d \n", count[p]);
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();
}
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::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;
}
}
}
#endif

View File

@ -1,311 +0,0 @@
#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

@ -1,172 +0,0 @@
#ifndef ENCOREANLAYZER_H
#define ENCOREANLAYZER_H
#include "Analyser.h"
#include "Isotope.h"
#include <map>
#include <QApplication>
// #include <QScreen>
namespace EncoreChMap{
const std::map<unsigned short, int> SN2Bd = {
{278, 0},
{45, 1},
{370, 2}
};
const int mapping[3][16] = {
// 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
{200, -1, 0, -1, 8, -1,300, -1,108, -1,102, -1,109, -1, 16, -1 },
{201, -1,110,107,111,106,112,105,113,104,114,103,115, -1,116,101 },
{202, 1, 15, 2, 14, 3, 13, 4, 12, 5, 11, 6, 10, 7, 9, -1 }
};
const double corr[16][3] = {
{ 1.00000, 1.00000, 1.00000},
{ 1.00000, 1.00000, 1.03158},
{ 1.00000, 1.00000, 0.99240},
{ 1.00000, 1.03704, 0.94004},
{ 1.01031, 1.02084, 1.10114},
{ 1.00000, 0.94685, 1.00513},
{ 1.00000, 1.03431, 1.00513},
{ 1.00000, 0.92670, 0.96078},
{ 1.03431, 0.94685, 0.96314},
{ 1.00000, 1.03158, 0.95145},
{ 0.95145, 1.00256, 0.97270},
{ 1.00000, 1.00256, 0.90950},
{ 1.03704, 0.99492, 0.98740},
{ 1.00000, 1.00000, 0.99746},
{ 0.96078, 1.03980, 1.00513},
{ 1.00000, 1.05095, 1.00000},
};
};
class Encore : public Analyzer{
Q_OBJECT
public:
Encore(Digitizer ** digi, unsigned int nDigi, QMainWindow * parent = nullptr): Analyzer(digi, nDigi, parent){
SetUpdateTimeInSec(1.0);
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);
SetUpCanvas();
}
// Encore(){};
void SetUpCanvas();
public slots:
void UpdateHistograms();
private:
MultiBuilder *evtbder;
Histogram2D * hLeft;
Histogram2D * hRight;
Histogram2D * hLR;
Histogram1D * hMulti;
QCheckBox * chkRunAnalyzer;
};
inline void Encore::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", 17, 0, 16, 200, 0, 20000, this);
layout->addWidget(hLeft, 1, 0);
hRight = new Histogram2D("Right", "Ch", "Energy", 17, 0, 16, 200, 0, 20000, this);
layout->addWidget(hRight, 1, 1);
hLR = new Histogram2D("Left + Right", "Ch", "Energy", 17, 0, 16, 200, 0, 20000, this);
layout->addWidget(hLR, 2, 0);
hMulti = new Histogram1D("Multi", "multiplicity", 40, 0, 40);
layout->addWidget(hMulti, 2, 1);
}
inline void Encore::UpdateHistograms(){
if( this->isVisible() == false ) return;
if( chkRunAnalyzer->isChecked() == false ) return;
BuildEvents(); // 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;
for( long i = eventStart ; i <= eventIndex; i ++ ){
std::vector<Hit> event = evtbder->events[i];
//printf("-------------- %ld\n", i);
hMulti->Fill((int) event.size());
//if( event.size() < 9 ) return;
if( event.size() == 0 ) return;
double sum[17] = {0};
for( int k = 0; k < (int) event.size(); k++ ){
int bd = EncoreChMap::SN2Bd.at(event[k].sn);
int ch = event[k].ch;
int ID = EncoreChMap::mapping[bd][ch];
if( ID < 0 ) continue;
double eC = event[k].energy;
if( 0 <= ID && ID < 100 ) {
eC *= EncoreChMap::corr[ch][bd];
hLeft->Fill(ID, eC);
sum[ID] += eC;
}
if( 100 <= ID && ID < 200 ) {
eC *= EncoreChMap::corr[ch][bd];
hRight->Fill(ID-100, eC );
sum[ID-100] += 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

View File

@ -1,537 +0,0 @@
/***********************************************************************
*
* This is Isotope.h, To extract the isotope mass from massXX.txt
*
*-------------------------------------------------------
* created by Ryan (Tsz Leung) Tang, Nov-18, 2018
* email: goluckyryan@gmail.com
* ********************************************************************/
#ifndef ISOTOPE_H
#define ISOTOPE_H
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h> //atoi
#include <algorithm>
#include <cmath>
using namespace std;
const double mp = 938.2720813; // MeV/c^2
const double mn = 939.56542052; // MeV/c^2
const double amu = 931.0;
const string massData="analyzers/mass20.txt";
// about the mass**.txt
// Mass Excess = (ATOMIC MASS - A)*amu | e.g. n : (1.088664.91585E-6-1)*amu
// mass excess uncertaintly
// BEA = (Z*M(1H) + N*M(1n) - Me(A,Z))/A , Me is the mass with electrons
// BEA = (Z*mp + N*mn - M(A,Z))/A , M is the mass without electrons
class Isotope {
public:
int A, Z;
double Mass, MassError, BEA;
string Name, Symbol;
string dataSource;
Isotope(){findHeliosPath();};
Isotope(int a, int z){ findHeliosPath();SetIso(a,z); };
Isotope(string name){ findHeliosPath(); SetIsoByName(name); };
void SetIso(int a, int z);
void SetIsoByName(string name);
double CalSp(int Np, int Nn); // this for the Np-proton, Nn-neutron removal
double CalSp2(int a, int z); // this is for (a,z) nucleus removal
double CalBeta(double T){
//double Etot = Mass + T;
double gamma = 1. + T/Mass;
double beta = sqrt(1. - 1. / gamma / gamma ) ;
return beta;
}
void Print();
void ListShell();
void SetMassTablePath(string path) {dataSource = path;}
string GetMassTablePath() const{ return dataSource;}
private:
void FindMassByAZ(int a, int z); // give mass, massError, BEA, Name, Symbol;
void FindMassByName(string name); // give Z, mass, massError, BEA;
int TwoJ(int nShell);
string Orbital(int nShell);
int magic(int i){
switch (i){
case 0: return 2; break;
case 1: return 8; break;
case 2: return 20; break;
case 3: return 28; break;
case 4: return 40; break;
case 5: return 50; break;
case 6: return 82; break;
case 7: return 128; break;
}
return 0;
}
int magicShellID(int i){
switch (i){
case 0: return 0; break;
case 1: return 2; break;
case 2: return 5; break;
case 3: return 6; break;
case 4: return 9; break;
case 5: return 10; break;
case 6: return 15; break;
case 7: return 21; break;
}
return 0;
}
int fileStartLine;
int fileEndLine;
int lineMass050_099;
int lineMass100_149;
int lineMass150_199;
int lineMass200;
void setFileLines(){
fileStartLine = 37;
fileEndLine = 3594;
lineMass050_099 = 466;
lineMass100_149 = 1160;
lineMass150_199 = 1994;
lineMass200 = 2774;
}
char * heliosPath;
bool isFindOnce;
void findHeliosPath(){
heliosPath = getenv("HELIOSSYS");
if( heliosPath ){
dataSource = heliosPath;
dataSource += "/analysis" + massData;
}else{
dataSource = massData;
}
}
};
inline void Isotope::SetIso(int a, int z){
this->A = a;
this->Z = z;
FindMassByAZ(a,z);
}
inline void Isotope::SetIsoByName(string name){
FindMassByName(name);
}
inline void Isotope::FindMassByAZ(int A, int Z){
string line;
int lineNum=0;
int list_A, list_Z;
ifstream myfile;
int flag=0;
setFileLines();
int numLineStart = fileStartLine;
int numLineEnd = fileEndLine;
if ( A >= 50 && A < 100) numLineStart = lineMass050_099;
if ( A >=100 && A < 150) numLineStart = lineMass100_149;
if ( A >=150 && A < 200) numLineStart = lineMass150_199;
if ( A >=200 ) numLineStart = lineMass200;
myfile.open(dataSource.c_str());
if (myfile.is_open()) {
while (/*! myfile.eof() &&*/ flag == 0 && lineNum <numLineEnd){
lineNum ++ ;
//printf("%3d ",lineNum);
getline (myfile,line);
if (lineNum >= numLineStart ){
list_Z = atoi((line.substr(10,5)).c_str());
list_A = atoi((line.substr(15,5)).c_str());
if ( A == list_A && Z == list_Z) {
this->BEA = atof((line.substr(54,11)).c_str());
this->Mass = list_Z*mp + (list_A-list_Z)*mn - this->BEA/1000*list_A;
this->MassError = atof((line.substr(65,7)).c_str());
string str = line.substr(20,2);
str.erase(remove(str.begin(), str.end(), ' '), str.end());
this->Symbol = str;
ostringstream ss;
ss << A << this->Symbol;
this->Name = ss.str();
flag = 1;
}else if ( list_A > A) {
this->BEA = -404;
this->Mass = -404;
this->MassError = -404;
this->Symbol = "non";
this->Name = "non";
break;
}
}
}
if( this->Name == "1H" ) this->Name = "p";
if( this->Name == "2H" ) this->Name = "d";
if( this->Name == "3H" ) this->Name = "t";
if( this->Name == "4He" ) this->Name = "a";
myfile.close();
}else {
printf("Unable to open %s\n", dataSource.c_str());
}
}
inline void Isotope::FindMassByName(string name){
// done seperate the Mass number and the name
if( name == "n" ) {
this->Name = "1n";
this->BEA = 0;
this->Mass = mn;
this->MassError = 0;
this->Name = "n";
this->A = 1;
this->Z = 0;
return;
}
if( name == "p" ) name = "1H";
if( name == "d" ) name = "2H";
if( name == "t" ) name = "3H";
if( name == "a" ) name = "4He";
string temp = name;
int lastDigit = 0;
for(int i=0; temp[i]; i++){
if(temp[i] == '0') lastDigit = i;
if(temp[i] == '1') lastDigit = i;
if(temp[i] == '2') lastDigit = i;
if(temp[i] == '3') lastDigit = i;
if(temp[i] == '4') lastDigit = i;
if(temp[i] == '5') lastDigit = i;
if(temp[i] == '6') lastDigit = i;
if(temp[i] == '7') lastDigit = i;
if(temp[i] == '8') lastDigit = i;
if(temp[i] == '9') lastDigit = i;
}
this->Symbol = temp.erase(0, lastDigit +1);
//check is Symbol is 2 charaters, if not, add " " at the end
if( this->Symbol.length() == 1 ){
this->Symbol = this->Symbol + " ";
}
temp = name;
int len = temp.length();
temp = temp.erase(lastDigit+1, len);
this->A = atoi(temp.c_str());
//printf(" Symbol = |%s| , Mass = %d\n", this->Symbol.c_str(), this->A);
// find the nucleus in the data
string line;
int lineNum=0;
int list_A;
string list_symbol;
ifstream myfile;
int flag=0;
setFileLines();
int numLineStart = fileStartLine;
int numLineEnd = fileEndLine;
if ( A >= 50 && A < 100) numLineStart = lineMass050_099;
if ( A >=100 && A < 150) numLineStart = lineMass100_149;
if ( A >=150 && A < 200) numLineStart = lineMass150_199;
if ( A >=200 ) numLineStart = lineMass200;
myfile.open(dataSource.c_str());
if (myfile.is_open()) {
while (/*! myfile.eof() &&*/ flag == 0 && lineNum <numLineEnd){
lineNum ++ ;
//printf("%3d ",lineNum);
getline (myfile,line);
if (lineNum >= numLineStart ){
list_symbol = line.substr(20,2);
list_A = atoi((line.substr(15,5)).c_str());
//printf(" A = %d, Sym = |%s| \n", list_A, list_symbol.c_str());
if ( this->A == list_A && this->Symbol == list_symbol) {
this->Z = atoi((line.substr(10,5)).c_str());
this->BEA = atof((line.substr(54,11)).c_str());
this->Mass = this->Z*mp + (list_A-this->Z)*mn - this->BEA/1000*list_A;
this->MassError = atof((line.substr(65,7)).c_str());
string str = line.substr(20,2);
str.erase(remove(str.begin(), str.end(), ' '), str.end());
this->Symbol = str;
ostringstream ss;
ss << this->A << this->Symbol;
this->Name = ss.str();
flag = 1;
}else if ( list_A > this->A) {
this->BEA = -404;
this->Mass = -404;
this->MassError = -404;
this->Symbol = "non";
this->Name = "non";
break;
}
}
}
myfile.close();
}else {
printf("Unable to open %s\n", dataSource.c_str());
}
}
inline double Isotope::CalSp(int Np, int Nn){
Isotope nucleusD(A - Np - Nn, Z - Np);
if( nucleusD.Mass != -404){
return nucleusD.Mass + Nn*mn + Np*mp - this->Mass;
}else{
return -404;
}
}
inline double Isotope::CalSp2(int a, int z){
Isotope nucleusD(A - a , Z - z);
Isotope nucleusS(a,z);
if( nucleusD.Mass != -404 && nucleusS.Mass != -404){
return nucleusD.Mass + nucleusS.Mass - this->Mass;
}else{
return -404;
}
}
inline int Isotope::TwoJ(int nShell){
switch(nShell){
case 0: return 1; break; // 0s1/2
case 1: return 3; break; // 0p3/2
case 2: return 1; break; // 0p1/2 -- 8
case 3: return 5; break; // 0d5/2
case 4: return 1; break; // 1s1/2
case 5: return 3; break; // 0d3/2 -- 20
case 6: return 7; break; // 0f7/2 -- 28
case 7: return 3; break; // 1p3/2
case 8: return 1; break; // 1p1/2
case 9: return 5; break; // 0f5/2 -- 40
case 10: return 9; break; // 0g9/2 -- 50
case 11: return 7; break; // 0g7/2
case 12: return 5; break; // 1d5/2
case 13: return 11; break; // 0h11/2
case 14: return 3; break; // 1d3/2
case 15: return 1; break; // 2s1/2 -- 82
case 16: return 9; break; // 0h9/2
case 17: return 7; break; // 1f7/2
case 18: return 13; break; // 0i13/2
case 19: return 3; break; // 2p3/2
case 20: return 5; break; // 1f5/2
case 21: return 1; break; // 1p1/2 -- 126
case 22: return 9; break; // 1g9/2
case 23: return 11; break; // 0i11/2
case 24: return 15; break; // 0j15/2
case 25: return 5; break; // 2d5/2
case 26: return 1; break; // 3s1/2
case 27: return 3; break; // 2d3/2
case 28: return 7; break; // 1g7/2
}
return 0;
}
inline string Isotope::Orbital(int nShell){
switch(nShell){
case 0: return "0s1 "; break; //
case 1: return "0p3 "; break; //
case 2: return "0p1 "; break; //-- 8
case 3: return "0d5 "; break; //
case 4: return "1s1 "; break; //
case 5: return "0d3 "; break; //-- 20
case 6: return "0f7 "; break; //-- 28
case 7: return "1p3 "; break; //
case 8: return "1p1 "; break; //
case 9: return "0f5 "; break; //-- 40
case 10: return "0g9 "; break; //-- 50
case 11: return "0g7 "; break; //
case 12: return "1d5 "; break; //
case 13: return "0h11"; break; //
case 14: return "1d3 "; break; //
case 15: return "2s1 "; break; //-- 82
case 16: return "0h9 "; break; //
case 17: return "1f7 "; break; //
case 18: return "0i13"; break; //
case 19: return "2p3 "; break; //
case 20: return "1f5 "; break; //
case 21: return "1p1 "; break; //-- 126
case 22: return "1g9 "; break; //
case 23: return "0i11"; break; //
case 24: return "0j15"; break; //
case 25: return "2d5 "; break; //
case 26: return "3s1 "; break; //
case 27: return "2d3 "; break; //
case 28: return "1g7 "; break; //
}
return "nan";
}
inline void Isotope::ListShell(){
if( Mass < 0 ) return;
int n = A-Z;
int p = Z;
int k = min(n,p);
int nMagic = 0;
for( int i = 0; i < 7; i++){
if( magic(i) < k && k <= magic(i+1) ){
nMagic = i;
break;
}
}
int coreShell = magicShellID(nMagic-1);
int coreZ1 = magic(nMagic-1);
int coreZ2 = magic(nMagic);
Isotope core1( 2*coreZ1, coreZ1);
Isotope core2( 2*coreZ2, coreZ2);
printf("------------------ Core:%3s, inner Core:%3s \n", (core2.Name).c_str(), (core1.Name).c_str());
printf(" || ");
int t = max(n,p);
int nShell = 0;
do{
int occ = TwoJ(nShell)+1;
if( nShell > coreShell) {
printf("%4s", Orbital(nShell).c_str());
if( nShell == 0 || nShell == 2 || nShell == 5 || nShell ==6 || nShell == 9 || nShell == 10 || nShell == 15 || nShell == 21){
printf("|");
}else{
printf(",");
}
}
t = t - occ;
nShell++;
}while( t > 0 && nShell < 29);
for( int i = 1; i <= 6; i++){
if (nShell < 28) {
printf("%4s,", Orbital(nShell).c_str());
}else if( nShell == 28 ) {
printf("%4s", Orbital(nShell).c_str());
}
nShell ++;
}
if (nShell < 29) printf("%4s", Orbital(nShell).c_str());
printf("\n");
printf(" Z = %3d || ", p);
nShell = 0;
do{
int occ = TwoJ(nShell)+1;
if( nShell > coreShell ){
if( p > occ ) {
printf("%-4d", occ);
if( nShell == 0 || nShell == 2 || nShell == 5 || nShell ==6 || nShell == 9 || nShell == 10 || nShell == 15 || nShell == 21){
printf("|");
}else{
printf(",");
}
}else{
printf("%-4d", p);
}
}
p = p - occ;
nShell++;
}while( p > 0 && nShell < 29);
printf("\n");
printf(" N = %3d || ", n);
nShell = 0;
do{
int occ = TwoJ(nShell)+1;
if ( nShell > coreShell ){
if( n > occ ) {
printf("%-4d", occ);
if( nShell == 0 || nShell == 2 || nShell == 5 || nShell ==6 || nShell == 9 || nShell == 10 || nShell == 15 || nShell == 21){
printf("|");
}else{
printf(",");
}
}else{
printf("%-4d", n);
}
}
n = n - occ;
nShell++;
}while( n > 0 && nShell < 29);
printf("\n");
printf("------------------ \n");
}
inline void Isotope::Print(){
if (Mass > 0){
findHeliosPath();
printf(" using mass data : %s \n", dataSource.c_str());
printf(" mass of \e[47m\e[31m%s\e[m nucleus (Z,A)=(%3d,%3d) is \e[47m\e[31m%12.5f\e[m MeV, BE/A=%7.5f MeV\n", Name.c_str(), Z, A, Mass, BEA/1000.);
printf(" total BE : %12.5f MeV\n",BEA*A/1000.);
printf(" mass in amu : %12.5f u\n",Mass/amu);
printf(" mass excess : %12.5f MeV\n", Mass + Z*0.510998950 - A*amu);
printf("-------------- Seperation energy \n");
printf(" S1p: %8.4f| S1n: %8.4f| S(2H ): %8.4f| S1p1n : %8.4f\n", CalSp(1, 0), CalSp(0, 1), CalSp2(2, 1), CalSp(1, 1));
printf(" S2p: %8.4f| S2n: %8.4f| S(3He): %8.4f| S(3H) : %8.4f\n", CalSp(2, 0), CalSp(0, 2), CalSp2(3, 2), CalSp2(3, 1));
printf(" S3p: %8.4f| S3n: %8.4f| S(4He): %8.4f|\n", CalSp(3, 0), CalSp(0, 3), CalSp2(4, 2));
printf(" S4p: %8.4f| S4n: %8.4f| \n", CalSp(4, 0), CalSp(0, 4));
}else{
printf("Error %6.0f, no nucleus with (Z,A) = (%3d,%3d). \n", Mass, Z, A);
}
}
#endif

View File

@ -1,178 +0,0 @@
#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

View File

@ -1,233 +0,0 @@
#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

@ -1,134 +0,0 @@
#ifndef RASIOR_h
#define RASIOR_h
/*********************************************
* This is online analyzer for RASIOR, ANL
*
* Created by Ryan @ 2023-10-16
*
* ******************************************/
#include "Analyser.h"
class RAISOR : public Analyzer{
public:
RAISOR(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);
//========== use the influx from the Analyzer
influx = new InfluxDB("https://fsunuc.physics.fsu.edu/influx/");
dataBaseName = "testing";
SetUpCanvas(); // see below
};
void SetUpCanvas();
public slots:
void UpdateHistograms();
private:
MultiBuilder *evtbder;
Histogram2D * hPID;
int tick2ns;
float dE, E;
unsigned long long dE_t, E_t;
};
inline void RAISOR::SetUpCanvas(){
setGeometry(0, 0, 500, 500);
//============ histograms
hPID = new Histogram2D("RAISOR", "E", "dE", 100, 0, 5000, 100, 0, 20000, this);
layout->addWidget(hPID, 0, 0);
}
inline void RAISOR::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> cutList = hPID->GetCutList();
const int nCut = cutList.count();
unsigned long long tMin[nCut] = {0xFFFFFFFFFFFFFFFF}, tMax[nCut] = {0};
unsigned int count[nCut]={0};
//============ Processing data and fill histograms
long eventIndex = evtbder->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];
//printf("-------------- %ld\n", i);
if( event.size() == 0 ) return;
for( int k = 0; k < (int) event.size(); k++ ){
//event[k].Print();
if( event[k].ch == 0 ) {dE = event[k].energy; dE_t = event[k].timestamp;}
if( event[k].ch == 1 ) {E = event[k].energy; E_t = event[k].timestamp;}
}
// printf("(E, dE) = (%f, %f)\n", E, dE);
hPID->Fill(E + RandomGauss(0, 100), dE+ RandomGauss(0, 100)); // x, y
//check events inside any Graphical cut and extract the rate
for(int p = 0; p < cutList.count(); p++ ){
if( cutList[p].isEmpty() ) continue;
if( cutList[p].containsPoint(QPointF(E, dE), Qt::OddEvenFill) ){
if( dE_t < tMin[p] ) tMin[p] = dE_t;
if( dE_t > tMax[p] ) tMax[p] = dE_t;
count[p] ++;
//printf(".... %d \n", count[p]);
}
}
}
hPID->UpdatePlot();
//========== output to Influx
QList<QString> cutNameList = hPID->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.toStdString());
influx->ClearDataPointsBuffer();
}
}
#endif

View File

@ -1,93 +0,0 @@
# 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

@ -1,447 +0,0 @@
#ifndef SPLITPOLEANLAYZER_H
#define SPLITPOLEANLAYZER_H
/*********************************************
* This is online analyzer for Split-Pole at FSU
*
* It is a template for other analyzer.
*
* Any new analyzer add to added to FSUDAQ.cpp
* 1) add include header
* 2) in OpenAnalyzer(), change the new
*
* add the source file in FSUDAQ_Qt6.pro then compile
* >qmake6 FSUDAQ_Qt6.pro
* >make
*
* ******************************************/
#include "SplitPoleHit.h"
#include "Analyser.h"
//^===========================================
//^===========================================
class SplitPole : public Analyzer{
Q_OBJECT
public:
SplitPole(Digitizer ** digi, unsigned int nDigi, QMainWindow * parent = nullptr): Analyzer(digi, nDigi, parent){
SetUpdateTimeInSec(1.0);
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.
mb->SetTimeWindow(3000);
//========== use the influx from the Analyzer
influx = new InfluxDB("https://fsunuc.physics.fsu.edu/influx/");
dataBaseName = "testing";
SetUpCanvas();
leTarget->setText("12C");
leBeam->setText("d");
leRecoil->setText("p");
sbBfield->setValue(0.75);
sbAngle->setValue(20);
sbEnergy->setValue(16);
hit.CalConstants(leTarget->text().toStdString(),
leBeam->text().toStdString(),
leRecoil->text().toStdString(), sbEnergy->value(), sbAngle->value());
hit.CalZoffset(sbBfield->value());
FillConstants();
hit.ClearData();
}
/// ~SplitPole(); // comment out = defalt destructor
void SetUpCanvas();
void FillConstants();
public slots:
void UpdateHistograms();
void ReplotHistograms();
private:
// declaie histograms
Histogram2D * hPID;
Histogram1D * h1;
Histogram1D * h1g;
Histogram1D * hMulti;
int tick2ns;
SplitPoleHit hit;
RSpinBox * sbBfield;
QLineEdit * leTarget;
QLineEdit * leBeam;
QLineEdit * leRecoil;
RSpinBox * sbEnergy;
RSpinBox * sbAngle;
RSpinBox * sbEventWin;
QCheckBox * chkRunAnalyzer;
QLineEdit * leMassTablePath;
QLineEdit * leQValue;
QLineEdit * leGSRho;
QLineEdit * leZoffset;
RSpinBox * sbRhoOffset;
RSpinBox * sbRhoScale;
};
inline void SplitPole::FillConstants(){
leQValue->setText(QString::number(hit.GetQ0()));
leGSRho->setText(QString::number(hit.GetRho0()*1000));
leZoffset->setText(QString::number(hit.GetZoffset()));
}
inline void SplitPole::SetUpCanvas(){
setGeometry(0, 0, 1600, 1000);
{//^====== magnet and reaction setting
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);
QLabel * lbBfield = new QLabel("B-field [T] ", box);
lbBfield->setAlignment(Qt::AlignRight | Qt::AlignCenter);
boxLayout->addWidget(lbBfield, 0, 2);
sbBfield = new RSpinBox(box);
sbBfield->setDecimals(3);
sbBfield->setSingleStep(0.05);
boxLayout->addWidget(sbBfield, 0, 3);
QLabel * lbTarget = new QLabel("Target ", box);
lbTarget->setAlignment(Qt::AlignRight | Qt::AlignCenter);
boxLayout->addWidget(lbTarget, 0, 0);
leTarget = new QLineEdit(box);
boxLayout->addWidget(leTarget, 0, 1);
QLabel * lbBeam = new QLabel("Beam ", box);
lbBeam->setAlignment(Qt::AlignRight | Qt::AlignCenter);
boxLayout->addWidget(lbBeam, 1, 0);
leBeam = new QLineEdit(box);
boxLayout->addWidget(leBeam, 1, 1);
QLabel * lbRecoil = new QLabel("Recoil ", box);
lbRecoil->setAlignment(Qt::AlignRight | Qt::AlignCenter);
boxLayout->addWidget(lbRecoil, 2, 0);
leRecoil = new QLineEdit(box);
boxLayout->addWidget(leRecoil, 2, 1);
QLabel * lbEnergy = new QLabel("Beam Energy [MeV] ", box);
lbEnergy->setAlignment(Qt::AlignRight | Qt::AlignCenter);
boxLayout->addWidget(lbEnergy, 1, 2);
sbEnergy = new RSpinBox(box);
sbEnergy->setDecimals(3);
sbEnergy->setSingleStep(1.0);
boxLayout->addWidget(sbEnergy, 1, 3);
QLabel * lbAngle = new QLabel("SPS Angle [Deg] ", box);
lbAngle->setAlignment(Qt::AlignRight | Qt::AlignCenter);
boxLayout->addWidget(lbAngle, 2, 2);
sbAngle = new RSpinBox(box);
sbAngle->setDecimals(3);
sbAngle->setSingleStep(1.0);
boxLayout->addWidget(sbAngle, 2, 3);
boxLayout->setColumnStretch(0, 1);
boxLayout->setColumnStretch(1, 2);
boxLayout->setColumnStretch(2, 1);
boxLayout->setColumnStretch(3, 2);
connect(leTarget, &QLineEdit::returnPressed, this, [=](){
hit.CalConstants(leTarget->text().toStdString(),
leBeam->text().toStdString(),
leRecoil->text().toStdString(), sbEnergy->value(), sbAngle->value() );
hit.CalZoffset(sbBfield->value());
FillConstants();
});
connect(leBeam, &QLineEdit::returnPressed, this, [=](){
hit.CalConstants(leTarget->text().toStdString(),
leBeam->text().toStdString(),
leRecoil->text().toStdString(), sbEnergy->value(), sbAngle->value());
hit.CalZoffset(sbBfield->value());
FillConstants();
});
connect(leRecoil, &QLineEdit::returnPressed, this, [=](){
hit.CalConstants(leTarget->text().toStdString(),
leBeam->text().toStdString(),
leRecoil->text().toStdString(), sbEnergy->value(), sbAngle->value());
hit.CalZoffset(sbBfield->value());
FillConstants();
});
connect(sbBfield, &RSpinBox::returnPressed, this, [=](){
hit.CalConstants(leTarget->text().toStdString(),
leBeam->text().toStdString(),
leRecoil->text().toStdString(), sbEnergy->value(), sbAngle->value());
hit.CalZoffset(sbBfield->value());
FillConstants();
});
connect(sbAngle, &RSpinBox::returnPressed, this, [=](){
hit.CalConstants(leTarget->text().toStdString(),
leBeam->text().toStdString(),
leRecoil->text().toStdString(), sbEnergy->value(), sbAngle->value());
hit.CalZoffset(sbBfield->value());
FillConstants();
});
connect(sbEnergy, &RSpinBox::returnPressed, this, [=](){
hit.CalConstants(leTarget->text().toStdString(),
leBeam->text().toStdString(),
leRecoil->text().toStdString(), sbEnergy->value(), sbAngle->value());
hit.CalZoffset(sbBfield->value());
FillConstants();
});
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);
separator->setFrameShadow(QFrame::Sunken);
boxLayout->addWidget(separator, 5, 0, 1, 4);
QLabel * lbMassTablePath = new QLabel("Mass Table Path : ", box);
lbMassTablePath->setAlignment(Qt::AlignRight | Qt::AlignCenter);
boxLayout->addWidget(lbMassTablePath, 6, 0);
leMassTablePath = new QLineEdit(QString::fromStdString(massData),box);
leMassTablePath->setReadOnly(true);
boxLayout->addWidget(leMassTablePath, 6, 1, 1, 3);
QLabel * lbQValue = new QLabel("Q-Value [MeV] ", box);
lbQValue->setAlignment(Qt::AlignRight | Qt::AlignCenter);
boxLayout->addWidget(lbQValue, 7, 0);
leQValue = new QLineEdit(box);
leQValue->setReadOnly(true);
boxLayout->addWidget(leQValue, 7, 1);
QLabel * lbGDRho = new QLabel("G.S. Rho [mm] ", box);
lbGDRho->setAlignment(Qt::AlignRight | Qt::AlignCenter);
boxLayout->addWidget(lbGDRho, 7, 2);
leGSRho = new QLineEdit(box);
leGSRho->setReadOnly(true);
boxLayout->addWidget(leGSRho, 7, 3);
QLabel * lbZoffset = new QLabel("Z-offset [mm] ", box);
lbZoffset->setAlignment(Qt::AlignRight | Qt::AlignCenter);
boxLayout->addWidget(lbZoffset, 8, 0);
leZoffset = new QLineEdit(box);
leZoffset->setReadOnly(true);
boxLayout->addWidget(leZoffset, 8, 1);
QFrame *separator1 = new QFrame(box);
separator1->setFrameShape(QFrame::HLine);
separator1->setFrameShadow(QFrame::Sunken);
boxLayout->addWidget(separator1, 9, 0, 1, 4);
QLabel * lbRhoOffset = new QLabel("Rho-offset [mm] ", box);
lbRhoOffset->setAlignment(Qt::AlignRight | Qt::AlignCenter);
boxLayout->addWidget(lbRhoOffset, 10, 0);
sbRhoOffset = new RSpinBox(box);
sbRhoOffset->setDecimals(2);
sbRhoOffset->setSingleStep(1);
sbRhoOffset->setValue(0);
boxLayout->addWidget(sbRhoOffset, 10, 1);
QLabel * lbRhoScale = new QLabel("Rho-Scaling ", box);
lbRhoScale->setAlignment(Qt::AlignRight | Qt::AlignCenter);
boxLayout->addWidget(lbRhoScale, 10, 2);
sbRhoScale = new RSpinBox(box);
sbRhoScale->setDecimals(2);
sbRhoScale->setSingleStep(0.01);
sbRhoScale->setMinimum(0.5);
sbRhoScale->setMaximum(1.5);
sbRhoScale->setValue(1.0);
boxLayout->addWidget(sbRhoScale, 10, 3);
QFrame *separator2 = new QFrame(box);
separator2->setFrameShape(QFrame::HLine);
separator2->setFrameShadow(QFrame::Sunken);
boxLayout->addWidget(separator2, 11, 0, 1, 4);
QString chMapStr = "ScinR = " + QString::number(SPS::ChMap::ScinR);
chMapStr += ", ScinL = " + QString::number(SPS::ChMap::ScinL);
chMapStr += ", dFR = " + QString::number(SPS::ChMap::dFR);
chMapStr += ", dFL = " + QString::number(SPS::ChMap::dFL);
chMapStr += ", dBR = " + QString::number(SPS::ChMap::dBR);
chMapStr += ", dBL = " + QString::number(SPS::ChMap::dBL);
chMapStr += ", Cathode = " + QString::number(SPS::ChMap::Cathode);
chMapStr += ", AnodeF = " + QString::number(SPS::ChMap::AnodeF);
chMapStr += ", AnodeB = " + QString::number(SPS::ChMap::AnodeB);
QLabel * chMapLabel = new QLabel(chMapStr, box);
boxLayout->addWidget(chMapLabel, 12, 0, 1, 4);
}
//============ histograms
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-Back", 100, 0, 20000, 100, 0, 40000, this);
//layout is inheriatge from Analyzer
layout->addWidget(hPID, 1, 0, 2, 1);
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)", "x1", 300, -200, 200, this);
layout->addWidget(h1g, 2, 1);
layout->setColumnStretch(0, 1);
layout->setColumnStretch(1, 1);
}
inline void SplitPole::UpdateHistograms(){
if( this->isVisible() == false ) return;
if( chkRunAnalyzer->isChecked() == false ) return;
BuildEvents(); // call the event builder to build events
//============ Get events, and do analysis
long eventBuilt = mb->eventBuilt;
if( eventBuilt == 0 ) return;
//============ Get the cut list, if any
QList<QPolygonF> cutList = hPID->GetCutList();
const int nCut = cutList.count();
unsigned long long tMin[nCut] = {0xFFFFFFFFFFFFFFFF}, tMax[nCut] = {0};
unsigned int count[nCut]={0};
//============ 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];
//printf("-------------- %ld\n", i);
hMulti->Fill((int) event.size());
//if( event.size() < 9 ) return;
if( event.size() == 0 ) return;
hit.ClearData();
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 + 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.eAB;
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;
if( cutList[p].containsPoint(QPointF(pidX, pidY), Qt::OddEvenFill) ){
if( tPidX < tMin[p] ) tMin[p] = tPidX;
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 ){
h1g->Fill(hit.x1);
}
}
}
}
QList<QString> cutNameList = hPID->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.toStdString());
influx->ClearDataPointsBuffer();
}
}
inline void SplitPole::ReplotHistograms(){
hPID->UpdatePlot();
h1->UpdatePlot();
hMulti->UpdatePlot();
h1g->UpdatePlot();
}
#endif

View File

@ -1,251 +0,0 @@
#ifndef SPLITPOLEHit_H
#define SPLITPOLEHit_H
#include "Isotope.h"
#include <cmath>
#include <random>
// static double randZeroToOne() {
// return static_cast<double>(rand()) / RAND_MAX;
// }
// // Box-Muller transform to generate random Gaussian numbers
// static double generateGaussian(double mean, double stddev) {
// static bool hasSpare = false;
// static double spare;
// if (hasSpare) {
// hasSpare = false;
// return mean + stddev * spare;
// } else {
// double u, v, s;
// do {
// u = 2.0 * randZeroToOne() - 1.0;
// v = 2.0 * randZeroToOne() - 1.0;
// s = u * u + v * v;
// } while (s >= 1.0 || s == 0.0);
// s = std::sqrt(-2.0 * std::log(s) / s);
// spare = v * s;
// hasSpare = true;
// return mean + stddev * u * s;
// }
// }
namespace SPS{
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.;
const double DISPERSION = 1.96; // x-position/rho
const double MAGNIFICATION = 0.39; // in x-position
const double X1X2Separation = 36; // cm
}
class SplitPoleHit{
public:
SplitPoleHit(){
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 eCath; unsigned long long tCath;
unsigned int eAF; unsigned long long tAF;
unsigned int eAB; unsigned long long tAB;
float eSAvg;
float x1, x2, theta;
double xAvg;
double GetQ0() const {return Q0;}
double GetRho0() const {return rho0;}
double GetZoffset() const {return zOffset;}
void SetMassTablePath(std::string path){
target.SetMassTablePath(path);
beam.SetMassTablePath(path);
recoil.SetMassTablePath(path);
heavyRecoil.SetMassTablePath(path);
}
void CalConstants(std::string targetStr, std::string beamStr, std::string recoilStr, double energyMeV, double angleDeg){
target.SetIsoByName(targetStr);
beam.SetIsoByName(beamStr);
recoil.SetIsoByName(recoilStr);
heavyRecoil.SetIso(target.A + beam.A - recoil.A, target.Z + beam.Z - recoil.Z);
angleDegree = angleDeg; // degree
beamKE = energyMeV; // MeV
Ei = target.Mass + beamKE + beam.Mass;
k1 = sqrt( 2*beam.Mass*beamKE + beamKE*beamKE);
cs = cos(angleDegree * SPS::deg2rad);
ma = recoil.Mass;
mb = heavyRecoil.Mass;
isConstantCal = true;
printf("============================================\n");
printf(" Beam Mass : %20.4f MeV/c2\n", beam.Mass);
printf(" beam KE : %20.4f MeV\n", beamKE);
printf("Target Mass : %20.4f MeV/c2\n", target.Mass);
printf("Recoil Mass : %20.4f MeV/c2\n", recoil.Mass);
printf("H. Rec Mass : %20.4f MeV/c2\n", heavyRecoil.Mass);
printf(" angle : %20.4f deg\n", angleDegree);
printf(" k1 : %20.4f MeV/c\n", k1);
printf(" Ei : %20.4f MeV\n", Ei);
}
double CalRecoilMomentum(double Ex){
if( !isConstantCal ) return 0;
double p = Ei*Ei - k1*k1;
double q = ma*ma - (mb + Ex)*(mb + Ex);
double x = k1* ( p + q) * cs;
double y = pow( p, 2) + pow(q, 2)- 2 * Ei * Ei * (ma* ma + (mb + Ex)*(mb + Ex)) + 2 * k1 * k1 * (ma*ma * cos(2* angleDegree * SPS::deg2rad) + (mb + Ex)*(mb + Ex));
double z = 2 * ( Ei*Ei - k1*k1 * cs * cs) ;
return (x + Ei * sqrt(y))/z;
}
double Momentum2Rho(double ka){
return ka / (recoil.Z * Bfield * SPS::c);
}
double Momentum2Ex(double ka){
return sqrt( Ei*Ei - k1*k1 + ma*ma + 2 * cs * k1 * ka - 2*Ei*sqrt(ma*ma + ka*ka)) - mb;
}
double Rho2Ex(double rhoInM){
double ka = rhoInM * (recoil.Z * Bfield * SPS::c);
return Momentum2Ex(ka);
}
void CalZoffset(double magFieldinT){
Bfield = magFieldinT;
if( !isConstantCal ) return;
double recoilP = CalRecoilMomentum(0);
Q0 = target.Mass + beam.Mass - recoil.Mass - heavyRecoil.Mass;
double recoilKE = sqrt(ma*ma + recoilP* recoilP) - ma;
printf("Q value : %f \n", Q0);
printf("recoil enegry for ground state: %f MeV = %f MeV/c\n", recoilKE, recoilP);
rho0 = recoilP/(recoil.Z * Bfield * SPS::c); // in m
double haha = sqrt( ma * beam.Mass * beamKE / recoilKE );
double k = haha * sin(angleDegree * SPS::deg2rad) / ( ma + mb - haha * cs);
zOffset = -100.0 * rho0 * k * SPS::DISPERSION * SPS::MAGNIFICATION;
printf("rho: %f m; z-offset: %f cm\n", rho0, zOffset);
}
void ClearData(){
eSR = 0; tSR = 0;
eSL = 0; tSL = 0;
eFR = 0; tFR = 0;
eFL = 0; tFL = 0;
eBR = 0; tBR = 0;
eBL = 0; tBL = 0;
eCath = 0; tCath = 0;
eAF = 0; tAF = 0;
eAB = 0; tAB = 0;
eSAvg = -1;
x1 = NAN;
x2 = NAN;
theta = NAN;
xAvg = NAN;
isConstantCal = false;
}
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 ) {
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)) {
if( x2 > x1 ) {
theta = atan((x2-x1)/SPS::X1X2Separation);
}else if(x2 < x1){
theta = SPS::pi + atan((x2-x1)/SPS::X1X2Separation);
}else{
theta = SPS::pi * 0.5;
}
double w1 = 0.5 - zOffset/4.28625;
xAvg = w1 * x1 + (1-w1)* x2;
}
}
private:
Isotope target;
Isotope beam;
Isotope recoil;
Isotope heavyRecoil;
double Bfield;
double angleDegree;
double beamKE;
double zOffset;
double Q0, rho0;
bool isConstantCal;
double Ei, k1, cs, ma, mb;
};
#endif

File diff suppressed because it is too large Load Diff

157
influxdb.cpp Normal file
View File

@ -0,0 +1,157 @@
#include "influxdb.h"
InfluxDB::InfluxDB(std::string url, bool verbose){
curl = curl_easy_init();
if( verbose) curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
SetURL(url);
respondCode = 0;
dataPoints = "";
}
InfluxDB::~InfluxDB(){
curl_easy_cleanup(curl);
}
void InfluxDB::SetURL(std::string url){
// check the last char of url is "/"
if( url.back() != '/') {
this->databaseIP = url + "/";
}else{
this->databaseIP = url;
}
}
bool InfluxDB::TestingConnection(){
CheckDatabases();
if( respond != CURLE_OK ) return false;
return true;
}
std::string InfluxDB::CheckDatabases(){
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_easy_setopt(curl, CURLOPT_URL, (databaseIP + "query").c_str());
std::string postFields="q=Show databases";
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, static_cast<long>(postFields.length()));
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postFields.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallBack);
std::string readBuffer;
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
Execute();
//printf("|%s|\n", readBuffer.c_str());
if( respond != CURLE_OK) return "";
databaseList.clear();
size_t pos = readBuffer.find("values");
if( pos > 0 ){
std::string kaka = readBuffer.substr(pos+8);
pos = kaka.find("}");
kaka = kaka.substr(0, pos);
int len = kaka.length();
bool startFlag = false;
std::string lala;
char yaya = '"';
for( int i = 0; i < len; i++){
if( startFlag == false && kaka[i] == yaya ) {
startFlag = true;
lala = "";
continue;
}
if( startFlag && kaka[i] == yaya ){
startFlag = false;
databaseList.push_back(lala);
continue;
}
if( startFlag ) lala += kaka[i];
}
}
return readBuffer;
}
std::string InfluxDB::Query(std::string databaseName, std::string query){
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_easy_setopt(curl, CURLOPT_URL, (databaseIP + "query?db=" + databaseName).c_str());
std::string postFields = "q=" + query;
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, static_cast<long>(postFields.length()));
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postFields.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallBack);
std::string readBuffer;
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
Execute();
//printf("|%s|\n", readBuffer.c_str());
return readBuffer;
}
void InfluxDB::CreateDatabase(std::string databaseName){
curl_easy_setopt(curl, CURLOPT_URL, (databaseIP + "query").c_str());
curl_easy_setopt(curl, CURLOPT_POST, 1);
std::string postFields = "q=CREATE DATABASE " + databaseName;
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, static_cast<long>(postFields.length()));
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postFields.c_str());
Execute();
}
void InfluxDB::AddDataPoint(std::string fullString){
dataPoints += fullString + "\n";
}
void InfluxDB::ClearDataPointsBuffer(){
dataPoints = "";
}
void InfluxDB::PrintDataPoints(){
printf("%s\n", dataPoints.c_str());
}
void InfluxDB::WriteData(std::string databaseName){
if( dataPoints.length() == 0 ) return;
//printf("|%s|\n", (databaseIP + "write?db=" + databaseName).c_str());
curl_easy_setopt(curl, CURLOPT_URL, (databaseIP + "write?db=" + databaseName).c_str());
curl_easy_setopt(curl, CURLOPT_POST, 1L);
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, static_cast<long>(dataPoints.length()));
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, dataPoints.c_str());
Execute();
}
void InfluxDB::Execute(){
try{
respond = curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &respondCode);
//printf("==== respond %d (OK = %d)\n", respond, CURLE_OK);
if( respond != CURLE_OK) printf("############# InfluxDB::Execute fail\n");
} catch (std::exception& e){ // in case of unexpected error
printf("%s\n", e.what());
respond = CURLE_SEND_ERROR;
}
}
size_t InfluxDB::WriteCallBack(char *contents, size_t size, size_t nmemb, void *userp){
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}

View File

@ -9,6 +9,8 @@
class InfluxDB{
private:
bool isURLValid;
CURL * curl;
CURLcode respond;
@ -16,16 +18,8 @@ class InfluxDB{
std::string databaseIP;
std::string dataPoints;
std::string token;
struct curl_slist * headers;
std::vector<std::string> databaseList;
unsigned short influxVersion;
std::string influxVersionStr;
bool connectionOK;
static size_t WriteCallBack(char *contents, size_t size, size_t nmemb, void *userp);
@ -34,21 +28,14 @@ class InfluxDB{
public:
InfluxDB(std::string url, bool verbose = false);
InfluxDB();
~InfluxDB();
void SetURL(std::string url);
void SetToken(std::string token);
bool TestingConnection(bool debug = false);
bool IsConnectionOK() const {return connectionOK;}
bool TestingConnection();
bool IsURLValid() const {return isURLValid;}
unsigned short GetVersionNo() const {return influxVersion;}
std::string GetVersionString() const {return influxVersionStr;}
/// Query, query will be in CSV format
std::string CheckInfluxVersion(bool debug = false);
/// Query
std::string CheckDatabases(); /// this save the list of database into databaseList
void PrintDataBaseList();
std::string Query(std::string databaseName, std::string query);
/// the CheckDatabases() function must be called before

54
macro.h
View File

@ -1,43 +1,23 @@
#ifndef MACRO_H
#define MACRO_H
#define MaxNPorts 4 //for optical link
#define MaxNBoards 4 //for both optical link and usb
#define MaxNPorts 4
#define MaxNBoards 4
#define MaxNDigitizer MaxNPorts * MaxNBoards
#define MaxRegChannel 16
#define MaxNChannels 64
#define MaxNChannels 16
#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 MaxDisplayTraceDataLength 2000 //data point,
#define MaxNumberOfTrace 4 // 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"
#include <sys/time.h> /** struct timeval, select() */
inline unsigned int getTime_us(){
inline unsigned int get_time(){
unsigned int time_us;
struct timeval t1;
struct timezone tz;
@ -46,26 +26,4 @@ inline unsigned int getTime_us(){
return time_us;
}
#include <chrono>
inline unsigned long long getTime_ns(){
std::chrono::high_resolution_clock::time_point currentTime = std::chrono::high_resolution_clock::now();
std::chrono::nanoseconds nanoseconds = std::chrono::duration_cast<std::chrono::nanoseconds>(currentTime.time_since_epoch());
return nanoseconds.count();
}
typedef unsigned short uShort;
typedef unsigned int uInt;
typedef unsigned long uLong;
typedef unsigned long long ullong;
#define DebugMode 0 //process check, when 1, print out all function call
// if DebugMode is 1, define DebugPrint() to be printf(), else, DebugPrint() define nothing
#if DebugMode
#define DebugPrint(fmt, ...) printf(fmt "::%s\n",##__VA_ARGS__, __func__);
#else
#define DebugPrint(fmt, ...)
#endif
#endif

View File

@ -1,81 +1,11 @@
#include <QApplication>
#include <QMessageBox>
#include <QProcess>
#include <QPushButton>
#include <QFile>
#include <QLocale>
#include "FSUDAQ.h"
#include <QObject>
#include <QDebug>
#include <sys/resource.h>
#include <csignal>
#include <cstdlib>
#include <iostream>
void abortHandler(int signal) {
std::cerr << "Signal received: " << signal << ", aborting..." << std::endl;
std::abort(); // Calls abort to generate core dump
}
#include <QApplication>
int main(int argc, char *argv[]){
std::signal(SIGSEGV, abortHandler);
setpriority(PRIO_PROCESS, 0, -20);
// CustomApplication a(argc, argv);
QApplication a(argc, argv);
// Set Locale
QLocale::setDefault(QLocale::system());
// Set Lock file
bool isLock = false;
int pid = 0;
QFile lockFile(DAQLockFile);
if( lockFile.open(QIODevice::Text | QIODevice::ReadOnly) ){
QTextStream in(&lockFile);
QString line = in.readLine();
isLock = line.toInt();
lockFile.close();
}
QFile pidFile(PIDFile);
if( pidFile.open(QIODevice::Text | QIODevice::ReadOnly)){
QTextStream in(&pidFile);
QString line = in.readLine();
pid = line.toInt();
pidFile.close();
}
if( isLock ) {
qDebug() << "The DAQ program is already opened. PID is " + QString::number(pid) + ", and delete the " + DAQLockFile ;
QMessageBox msgBox;
msgBox.setWindowTitle("Oopss....");
msgBox.setText("The DAQ program is already opened, or crashed perviously. \nPID is " + QString::number(pid) + "\n You can kill the procee by \"kill -9 <pid>\" and delete the " + DAQLockFile + "\n or click the \"Kill\" button");
msgBox.setIcon(QMessageBox::Information);
QPushButton * kill = msgBox.addButton("Kill and Open New", QMessageBox::AcceptRole);
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setDefaultButton(QMessageBox::Ok);
msgBox.exec();
if(msgBox.clickedButton() == kill){
remove(DAQLockFile);
QProcess::execute("kill", QStringList() << "-9" << QString::number(pid));
}else{
return 0;
}
}
lockFile.open(QIODevice::Text | QIODevice::WriteOnly);
lockFile.write( "1" );
lockFile.close();
pidFile.open(QIODevice::Text | QIODevice::WriteOnly);
pidFile.write( QString::number(QCoreApplication::applicationPid() ).toStdString().c_str() );
pidFile.close();
FSUDAQ w;
MainWindow w;
w.show();
return a.exec();
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

317
test.cpp Normal file
View File

@ -0,0 +1,317 @@
#include "macro.h"
#include "ClassData.h"
#include "ClassDigitizer.h"
#include <TROOT.h>
#include <TSystem.h>
#include <TApplication.h>
#include <TCanvas.h>
#include <TGraph.h>
#include <TH1.h>
#include <TFile.h>
#include <TTree.h>
#include <sys/time.h> /** struct timeval, select() */
#include <termios.h> /** tcgetattr(), tcsetattr() */
#include <vector>
static struct termios g_old_kbd_mode;
static void cooked(void);
static void uncooked(void);
static void raw(void);
int keyboardhit();
int getch(void);
//^======================================
int main(int argc, char* argv[]){
const int nBoard = 1;
Digitizer **dig = new Digitizer *[nBoard];
for( int i = 0 ; i < nBoard; i++){
int board = i % 3;
int port = i/3;
dig[i] = new Digitizer(board, port, false, true);
}
const float ch2ns = dig[0]->GetCh2ns();
Data * data = dig[0]->GetData();
data->OpenSaveFile("haha");
printf("################# DPP Type : %d , %s\n", data->DPPType, data->DPPTypeStr.c_str());
dig[0]->StartACQ();
for( int i = 0; i < 5; i ++ ){
usleep(100*1000);
dig[0]->ReadData();
data->DecodeBuffer(false, 5);
data->PrintStat();
data->SaveData();
int index = data->NumEventsDecoded[0];
printf("-------------- %ld \n", data->Waveform1[0][index].size());
}
dig[0]->StopACQ();
data->PrintAllData();
/*
TApplication * app = new TApplication("app", &argc, argv);
TCanvas * canvas = new TCanvas("c", "haha", 1200, 400);
canvas->Divide(3, 1);
TH1F * h1 = new TH1F("h1", "count", dig[0]->GetNChannel(), 0, dig[0]->GetNChannel());
TH1F * h2 = new TH1F("h2", "energy ch-0", 400, 0, 40000);
TGraph * g1 = new TGraph();
canvas->cd(1); h1->Draw("hist");
canvas->cd(2); h2->Draw();
canvas->cd(3); g1->Draw("AP");
Data * data = dig[0]->GetData();
data->Allocate80MBMemory();
remove("test.bin");
dig[0]->StartACQ();
std::vector<unsigned short> haha ;
uint32_t PreviousTime = get_time();
uint32_t CurrentTime = 0;
uint32_t ElapsedTime = 0;
int waveFormLength = dig[0]->ReadRegister(Register::DPP::RecordLength_G);
while(true){
if(keyboardhit()) {
break;
}
usleep(1000);
dig[0]->ReadData();
if( data->nByte > 0 ){
data->SaveBuffer("test");
data->DecodeBuffer(0);
unsigned short nData = data->EventIndex[0]; //channel-0
haha = data->Waveform1[0][nData-1];
for( int i = 0; i < waveFormLength; i++) g1->SetPoint(i, i*ch2ns, haha[i]);
canvas->cd(3); g1->Draw("AP");
canvas->Modified();
canvas->Update();
gSystem->ProcessEvents();
}
CurrentTime = get_time();
ElapsedTime = CurrentTime - PreviousTime; /// milliseconds
if( ElapsedTime > 1000 ){
int temp = system("clear");
data->PrintStat();
for(int i = 0; i < dig[0]->GetNChannel(); i++){
h1->Fill(i, data->EventIndex[i]);
}
for( int i = 0; i < data->EventIndex[0]; i++){
h2->Fill( data->Energy[0][i]);
}
data->ClearData();
canvas->cd(1); h1->Draw("hist");
canvas->cd(2); h2->Draw();
canvas->Modified();
canvas->Update();
gSystem->ProcessEvents();
PreviousTime = CurrentTime;
printf("Press any key to Stop\n");
}
}
app->Run();
*/
printf("Closing digitizers..............\n");
for( int i = 0; i < nBoard; i++){
if(dig[i]->IsConnected()) dig[i]->StopACQ();
delete dig[i];
}
delete [] dig;
/*********************/
/**////##################### Demo for loading and change setting without open a digitizer
/**
Digitizer * dig = new Digitizer();
dig->OpenDigitizer(0, 1, false, true);
dig->LoadSettingBinaryToMemory("expDir/settings/setting_323.bin");
//dig->ProgramPHABoard();
//dig->OpenSettingBinary("setting_323.bin");
//dig->ReadAllSettingsFromBoard();
//dig->PrintSettingFromMemory();
//dig->StopACQ();
//dig->WriteRegister(Register::DPP::SoftwareClear_W, 1);
printf("========== %d \n", dig->ReadSettingFromFile(Register::DPP::MaxAggregatePerBlockTransfer));
///dig->SaveSettingAsText("haha.txt");
///std::remove("Test_323_139_000.fsu");
//printf("========== %d \n", dig->ReadRegister(Register::DPP::MaxAggregatePerBlockTransfer));
delete dig;
/**
{///============ Checking the buffer size calculation
unsigned short B = 10; /// BLT
unsigned short Eg = 511; /// Event / dual channel
bool DT = 1; /// dual trace
bool E2 = 1; /// extra 2;
bool Wr = 1; /// wave record;
unsigned short AP2 = 0; /// 00 = input, 01 = Threshold, 10 = Trapezoid - Baseline, 11 = baseline
unsigned short AP1 = 1; /// 00 = input, 01 = RC-CR, 10 = RC-CR2, 11 = Trapezoid
unsigned short DP1 = 0x0000; /// peaking,
unsigned short RL = 100; /// record Length
unsigned short AO = 0x0;
for( int i = 0; i < dig->GetNChannel(); i++){
dig->WriteRegister(Register::DPP::NumberEventsPerAggregate_G, Eg, i);
dig->WriteRegister(Register::DPP::RecordLength_G, RL, i);
}
dig->WriteRegister(Register::DPP::MaxAggregatePerBlockTransfer, B);
dig->WriteRegister(Register::DPP::AggregateOrganization, AO);
uint32_t bit = 0x0C0115;
bit += (DT << 11);
bit += (AP1 << 12);
bit += (AP2 << 14);
bit += (Wr << 16);
bit += (E2 << 17);
bit += (DP1 << 20);
printf("---- Bd Config : 0x%08X \n", bit);
dig->WriteRegister(Register::DPP::BoardConfiguration, bit);
unsigned int bSize = dig->CalByteForBuffer();
int bbbb = (((2 + E2 + Wr*RL*4) * Eg + 2)*8 + 2)*B *4 *2 + 4 * 4;
printf("=========== exp Buffer size : %8u byte \n", bbbb);
usleep(1e6);
///using CAEN method
char * buffer = NULL;
uint32_t size;
CAEN_DGTZ_MallocReadoutBuffer(dig->GetHandle(), (char **)& buffer, &size);
printf("CAEN calculated Buffer Size : %8u byte = %.2f MB \n", size, size/1024./1024.);
printf(" diff : %8u byte \n", size > 2*bSize ? size - 2*bSize : 2*bSize - size);
delete buffer;
}/**/
//dig->GetData()->SetSaveWaveToMemory(true);
//dig->StartACQ();
//
//for( int i = 0; i < 60; i++){
// usleep(500*1000);
// dig->ReadData();
// printf("------------------- %d\n", i);
// unsigned long time1 = get_time();
// dig->GetData()->DecodeBuffer(false,0);
// unsigned long time2 = get_time();
// printf("********************* decode time : %lu usec\n", time2-time1);
// dig->GetData()->PrintStat();
// //dig->GetData()->SaveBuffer("Test");
//}
//
//dig->StopACQ();
return 0;
}
//*********************************
//*********************************
static void cooked(void){
tcsetattr(0, TCSANOW, &g_old_kbd_mode);
}
static void uncooked(void){
struct termios new_kbd_mode;
/** put keyboard (stdin, actually) in raw, unbuffered mode */
tcgetattr(0, &g_old_kbd_mode);
memcpy(&new_kbd_mode, &g_old_kbd_mode, sizeof(struct termios));
new_kbd_mode.c_lflag &= ~(ICANON | ECHO);
new_kbd_mode.c_cc[VTIME] = 0;
new_kbd_mode.c_cc[VMIN] = 1;
tcsetattr(0, TCSANOW, &new_kbd_mode);
}
static void raw(void){
static char init;
if(init) return;
/** put keyboard (stdin, actually) in raw, unbuffered mode */
uncooked();
/** when we exit, go back to normal, "cooked" mode */
atexit(cooked);
init = 1;
}
int keyboardhit(){
struct timeval timeout;
fd_set read_handles;
int status;
raw();
/** check stdin (fd 0) for activity */
FD_ZERO(&read_handles);
FD_SET(0, &read_handles);
timeout.tv_sec = timeout.tv_usec = 0;
status = select(0 + 1, &read_handles, NULL, NULL, &timeout);
if(status < 0){
printf("select() failed in keyboardhit()\n");
exit(1);
}
return (status);
}
int getch(void){
unsigned char temp;
raw();
/** stdin = fd 0 */
if(read(0, &temp, 1) != 1) return 0;
return temp;
}

View File

@ -8,12 +8,12 @@
#include "CAENDigitizer.h"
#include "CAENDigitizerType.h"
#include "../macro.h"
#include "../RegisterAddress.h"
#include "macro.h"
#include "RegisterAddress.h"
using namespace std;
void PrintChannelSettingFromDigitizer(int handle, int ch, float tick2ns){
void PrintChannelSettingFromDigitizer(int handle, int ch, float ch2ns){
printf("\e[33m================================================\n");
printf("================ Setting for channel %d \n", ch);
@ -48,11 +48,11 @@ void PrintChannelSettingFromDigitizer(int handle, int ch, float tick2ns){
default: extra2WordOptStr = "Reserved"; break;
}
printf(" tick2ns : %.0f ns\n", tick2ns);
printf(" ch2ns : %.0f ns\n", ch2ns);
printf("==========----- input \n");
CAEN_DGTZ_ReadRegister(handle, DPP::RecordLength_G + (ch << 8), value); printf("%24s %5d samples = %5.0f ns \n", "Record Length", ((value[0] * 8) & MaxRecordLength), ((value[0] * 8) & MaxRecordLength) * tick2ns); ///Record length
CAEN_DGTZ_ReadRegister(handle, DPP::PreTrigger + (ch << 8), value); printf("%24s %5d samples = %5.0f ns \n", "Pre-tigger", value[0] * 4, value[0] * 4 * tick2ns); ///Pre-trigger
CAEN_DGTZ_ReadRegister(handle, DPP::RecordLength_G + (ch << 8), value); printf("%24s %5d samples = %5.0f ns \n", "Record Length", ((value[0] * 8) & MaxRecordLength), ((value[0] * 8) & MaxRecordLength) * ch2ns); ///Record length
CAEN_DGTZ_ReadRegister(handle, DPP::PreTrigger + (ch << 8), value); printf("%24s %5d samples = %5.0f ns \n", "Pre-tigger", value[0] * 4, value[0] * 4 * ch2ns); ///Pre-trigger
printf("%24s %5.0f samples, DPP-[20:22]\n", "baseline mean", pow(4, 1 + baseline)); ///Ns baseline
CAEN_DGTZ_ReadRegister(handle, DPP::ChannelDCOffset + (ch << 8), value); printf("%24s %.2f %% \n", "DC offset", 100.0 - value[0] * 100./ 0xFFFF); ///DC offset
CAEN_DGTZ_ReadRegister(handle, DPP::InputDynamicRange + (ch << 8), value); printf("%24s %.1f Vpp \n", "input Dynamic", value[0] == 0 ? 2 : 0.5); ///InputDynamic
@ -60,27 +60,27 @@ void PrintChannelSettingFromDigitizer(int handle, int ch, float tick2ns){
printf("==========----- discriminator \n");
CAEN_DGTZ_ReadRegister(handle, DPP::PHA::TriggerThreshold + (ch << 8), value); printf("%24s %4d LSB\n", "Threshold", value[0]); ///Threshold
CAEN_DGTZ_ReadRegister(handle, DPP::PHA::TriggerHoldOffWidth + (ch << 8), value); printf("%24s %4d samples, %5.0f ns \n", "trigger hold off", value[0], value[0] * 4 * tick2ns); ///Trigger Hold off
CAEN_DGTZ_ReadRegister(handle, DPP::PHA::RCCR2SmoothingFactor + (ch << 8), value); printf("%24s %4d samples, %5.0f ns \n", "Fast Dis. smoothing", (value[0] & 0x1f) * 2, (value[0] & 0x1f) * 2 * tick2ns ); ///Fast Discriminator smoothing
CAEN_DGTZ_ReadRegister(handle, DPP::PHA::ShapedTriggerWidth + (ch << 8), value); printf("%24s %4d samples, %5.0f ns \n", "Fast Dis. output width", value[0], value[0] * 4 * tick2ns); ///Fast Dis. output width
CAEN_DGTZ_ReadRegister(handle, DPP::PHA::InputRiseTime + (ch << 8), value); printf("%24s %4d samples, %5.0f ns \n", "Input rise time ", value[0], value[0] * 4 * tick2ns); ///Input rise time
CAEN_DGTZ_ReadRegister(handle, DPP::PHA::TriggerHoldOffWidth + (ch << 8), value); printf("%24s %4d samples, %5.0f ns \n", "trigger hold off", value[0], value[0] * 4 * ch2ns); ///Trigger Hold off
CAEN_DGTZ_ReadRegister(handle, DPP::PHA::RCCR2SmoothingFactor + (ch << 8), value); printf("%24s %4d samples, %5.0f ns \n", "Fast Dis. smoothing", (value[0] & 0x1f) * 2, (value[0] & 0x1f) * 2 * ch2ns ); ///Fast Discriminator smoothing
CAEN_DGTZ_ReadRegister(handle, DPP::PHA::ShapedTriggerWidth + (ch << 8), value); printf("%24s %4d samples, %5.0f ns \n", "Fast Dis. output width", value[0], value[0] * 4 * ch2ns); ///Fast Dis. output width
CAEN_DGTZ_ReadRegister(handle, DPP::PHA::InputRiseTime + (ch << 8), value); printf("%24s %4d samples, %5.0f ns \n", "Input rise time ", value[0], value[0] * 4 * ch2ns); ///Input rise time
printf("==========----- Trapezoid \n");
CAEN_DGTZ_ReadRegister(handle, DPP::PHA::TrapezoidRiseTime + (ch << 8), value); printf("%24s %4d samples, %5.0f ns \n", "Trap. rise time", value[0], value[0] * 4 * tick2ns); ///Trap. rise time, 2 for 1 ch to 2ns
int riseTime = value[0] * 4 * tick2ns;
CAEN_DGTZ_ReadRegister(handle, DPP::PHA::TrapezoidFlatTop + (ch << 8), value); printf("%24s %4d samples, %5.0f ns \n", "Trap. flat time", value[0], value[0] * 4 * tick2ns); ///Trap. flat time
int flatTopTime = value[0] * 4 * tick2ns;
CAEN_DGTZ_ReadRegister(handle, DPP::PHA::TrapezoidRiseTime + (ch << 8), value); printf("%24s %4d samples, %5.0f ns \n", "Trap. rise time", value[0], value[0] * 4 * ch2ns); ///Trap. rise time, 2 for 1 ch to 2ns
int riseTime = value[0] * 4 * ch2ns;
CAEN_DGTZ_ReadRegister(handle, DPP::PHA::TrapezoidFlatTop + (ch << 8), value); printf("%24s %4d samples, %5.0f ns \n", "Trap. flat time", value[0], value[0] * 4 * ch2ns); ///Trap. flat time
int flatTopTime = value[0] * 4 * ch2ns;
double shift = log(riseTime * flatTopTime ) / log(2) - 2;
printf("%24s %4d bit =? %.1f = Ceil( Log(rise [ns] x decay [ns])/Log(2) ), DPP-[0:5]\n", "Trap. Rescaling", trapRescaling, shift ); ///Trap. Rescaling Factor
CAEN_DGTZ_ReadRegister(handle, DPP::PHA::DecayTime + (ch << 8), value); printf("%24s %4d samples, %5.0f ns \n", "Decay time", value[0], value[0] * 4 * tick2ns); ///Trap. pole zero
CAEN_DGTZ_ReadRegister(handle, DPP::PHA::PeakingTime + (ch << 8), value); printf("%24s %4d samples, %5.0f ns = %.2f %% of FlatTop\n", "Peaking time", value[0], value[0] * 4 * tick2ns, value[0] * 400. * tick2ns / flatTopTime ); ///Peaking time
CAEN_DGTZ_ReadRegister(handle, DPP::PHA::PeakHoldOff + (ch << 8), value); printf("%24s %4d samples, %5.0f ns \n", "Peak hole off", value[0], value[0] * 4 *tick2ns ); ///Peak hold off
CAEN_DGTZ_ReadRegister(handle, DPP::PHA::DecayTime + (ch << 8), value); printf("%24s %4d samples, %5.0f ns \n", "Decay time", value[0], value[0] * 4 * ch2ns); ///Trap. pole zero
CAEN_DGTZ_ReadRegister(handle, DPP::PHA::PeakingTime + (ch << 8), value); printf("%24s %4d samples, %5.0f ns = %.2f %% of FlatTop\n", "Peaking time", value[0], value[0] * 4 * ch2ns, value[0] * 400. * ch2ns / flatTopTime ); ///Peaking time
CAEN_DGTZ_ReadRegister(handle, DPP::PHA::PeakHoldOff + (ch << 8), value); printf("%24s %4d samples, %5.0f ns \n", "Peak hole off", value[0], value[0] * 4 *ch2ns ); ///Peak hold off
printf("%24s %4.0f samples, DPP-[12:13]\n", "Peak mean", pow(4, NsPeak)); ///Ns peak
printf("==========----- Other \n");
CAEN_DGTZ_ReadRegister(handle, DPP::PHA::FineGain + (ch << 8), value); printf("%24s %d = 0x%x\n", "Energy fine gain", value[0], value[0]); ///Energy fine gain
CAEN_DGTZ_ReadRegister(handle, DPP::ChannelADCTemperature_R + (ch << 8), value); printf("%24s %d C\n", "Temperature", value[0]); ///Temperature
CAEN_DGTZ_ReadRegister(handle, DPP::PHA::RiseTimeValidationWindow + (ch << 8), value); printf("%24s %.0f ns \n", "RiseTime Vaild Win.", value[0] * tick2ns);
CAEN_DGTZ_ReadRegister(handle, DPP::PHA::RiseTimeValidationWindow + (ch << 8), value); printf("%24s %.0f ns \n", "RiseTime Vaild Win.", value[0] * ch2ns);
CAEN_DGTZ_ReadRegister(handle, DPP::PHA::ChannelStopAcquisition + (ch << 8), value); printf("%24s %d = %s \n", "Stop Acq bit", value[0] & 1 , (value[0] & 1 ) == 0 ? "Run" : "Stop");
CAEN_DGTZ_ReadRegister(handle, DPP::ChannelStatus_R + (ch << 8), value); printf("%24s 0x%x \n", "Status bit", (value[0] & 0xff) );
CAEN_DGTZ_ReadRegister(handle, DPP::AMCFirmwareRevision_R + (ch << 8), value); printf("%24s 0x%x \n", "AMC firmware rev.", value[0] );
@ -175,26 +175,24 @@ int main(int argc, char* argv[]){
int handle;
printf("======== open board\n");
//int ret = CAEN_DGTZ_OpenDigitizer(CAEN_DGTZ_OpticalLink, 1, 0, 0, &handle);
int ret = CAEN_DGTZ_OpenDigitizer(CAEN_DGTZ_USB_A4818, 26006, 0, 0, &handle);
int ret = CAEN_DGTZ_OpenDigitizer(CAEN_DGTZ_OpticalLink, 1, 0, 0, &handle);
CAEN_DGTZ_BoardInfo_t BoardInfo;
ret = (int) CAEN_DGTZ_GetInfo(handle, &BoardInfo);
int NInputCh = BoardInfo.Channels;
uint32_t regChannelMask = 0xFFFF;
float tick2ns = 4.0;
int NChannel = BoardInfo.Channels;
uint32_t channelMask = 0xFFFF;
float ch2ns = 4.0;
switch(BoardInfo.Model){
case CAEN_DGTZ_V1730: tick2ns = 2.0; break; ///ns -> 500 MSamples/s
case CAEN_DGTZ_V1725: tick2ns = 4.0; break; ///ns -> 250 MSamples/s
case CAEN_DGTZ_V1730: ch2ns = 2.0; break; ///ns -> 500 MSamples/s
case CAEN_DGTZ_V1725: ch2ns = 4.0; break; ///ns -> 250 MSamples/s
}
unsigned int ADCbits = BoardInfo.ADC_NBits;
if( ret != 0 ) { printf("==== open digitizer fail.\n"); return 0;}
if( ret != 0 ) { printf("==== open digitizer\n"); return 0;}
///======= reset
ret = CAEN_DGTZ_Reset(handle);
/*
printf("======== program board\n");
///ret |= CAEN_DGTZ_SetDPPAcquisitionMode(handle, CAEN_DGTZ_DPP_ACQ_MODE_List, CAEN_DGTZ_DPP_SAVE_PARAM_EnergyAndTime);
@ -215,13 +213,12 @@ int main(int argc, char* argv[]){
/// Set the I/O level (CAEN_DGTZ_IOLevel_NIM or CAEN_DGTZ_IOLevel_TTL)
ret |= CAEN_DGTZ_SetIOLevel(handle, CAEN_DGTZ_IOLevel_NIM);
// Set the digitizer's behaviour when an external trigger arrives:
// CAEN_DGTZ_TRGMODE_DISABLED: do nothing
// CAEN_DGTZ_TRGMODE_EXTOUT_ONLY: generate the Trigger Output signal
// CAEN_DGTZ_TRGMODE_ACQ_ONLY = generate acquisition trigger
// CAEN_DGTZ_TRGMODE_ACQ_AND_EXTOUT = generate both Trigger Output and acquisition trigger
// see CAENDigitizer user manual, chapter "Trigger configuration" for details
/** Set the digitizer's behaviour when an external trigger arrives:
CAEN_DGTZ_TRGMODE_DISABLED: do nothing
CAEN_DGTZ_TRGMODE_EXTOUT_ONLY: generate the Trigger Output signal
CAEN_DGTZ_TRGMODE_ACQ_ONLY = generate acquisition trigger
CAEN_DGTZ_TRGMODE_ACQ_AND_EXTOUT = generate both Trigger Output and acquisition trigger
see CAENDigitizer user manual, chapter "Trigger configuration" for details */
ret |= CAEN_DGTZ_SetExtTriggerInputMode(handle, CAEN_DGTZ_TRGMODE_ACQ_ONLY);
if( ret != 0 ) { printf("==== CAEN_DGTZ_SetExtTriggerInputMode.\n"); return 0;}
@ -235,15 +232,15 @@ int main(int argc, char* argv[]){
//if( ret != 0 ) { printf("==== CAEN_DGTZ_SetDPPEventAggregation. %d\n", ret); return 0;}
// Set the mode used to syncronize the acquisition between different boards.
// In this example the sync is disabled
/** Set the mode used to syncronize the acquisition between different boards.
In this example the sync is disabled */
ret = CAEN_DGTZ_SetRunSynchronizationMode(handle, CAEN_DGTZ_RUN_SYNC_Disabled);
if( ret != 0 ) { printf("==== set board error.\n"); return 0;}
printf("======== program Channels\n");
///CAEN_DGTZ_DPP_PHA_Params_t DPPParams;
///memset(&DPPParams, 0, sizeof(CAEN_DGTZ_DPP_PHA_Params_t));
///for(int i = 0; i < NInputCh; i++){
///for(int i = 0; i < NChannel; i++){
/// DPPParams.M[i] = 5000; /// decay time [ns]
/// DPPParams.m[i] = 992; /// flat-top [ns]
/// DPPParams.k[i] = 96; /// rise-time [ns]
@ -262,7 +259,7 @@ int main(int argc, char* argv[]){
/// DPPParams.decimation[i] = 0 ; /// waveform decimation, 2^n, when n = 0, disable
/// DPPParams.blho[i] = 0; /// not use
///}
///ret = CAEN_DGTZ_SetDPPParameters(handle, regChannelMask, &DPPParams);
///ret = CAEN_DGTZ_SetDPPParameters(handle, channelMask, &DPPParams);
ret |= CAEN_DGTZ_WriteRegister(handle, DPP::PHA::DecayTime + 0x7000 , 5000 );
ret |= CAEN_DGTZ_WriteRegister(handle, DPP::PHA::TrapezoidFlatTop + 0x7000 , 62 );
@ -295,16 +292,16 @@ int main(int argc, char* argv[]){
int Nb; /// number of byte
char *buffer = NULL; /// readout buffer
uint32_t DataIndex[MaxRegChannel];
uint32_t EventIndex[MaxNChannels];
uint32_t AllocatedSize, BufferSize;
CAEN_DGTZ_DPP_PHA_Event_t *Events[MaxRegChannel]; /// events buffer
CAEN_DGTZ_DPP_PHA_Waveforms_t *Waveform[MaxRegChannel]; /// waveforms buffer
CAEN_DGTZ_DPP_PHA_Event_t *Events[MaxNChannels]; /// events buffer
CAEN_DGTZ_DPP_PHA_Waveforms_t *Waveform[MaxNChannels]; /// waveforms buffer
ret = CAEN_DGTZ_MallocReadoutBuffer(handle, &buffer, &AllocatedSize);
printf("allowcated %d byte ( %d words) for buffer\n", AllocatedSize, AllocatedSize/4);
ret |= CAEN_DGTZ_MallocDPPEvents(handle, reinterpret_cast<void**>(&Events), &AllocatedSize) ;
printf("allowcated %d byte for Events\n", AllocatedSize);
for( int i = 0 ; i < NInputCh; i++){
for( int i = 0 ; i < NChannel; i++){
ret |= CAEN_DGTZ_MallocDPPWaveforms(handle, reinterpret_cast<void**>(&Waveform[i]), &AllocatedSize);
printf("allowcated %d byte for waveform-%d\n", AllocatedSize, i);
}
@ -312,7 +309,7 @@ int main(int argc, char* argv[]){
if( ret != 0 ) { printf("==== memory allocation error.\n"); return 0;}
PrintBoardConfiguration(handle);
PrintChannelSettingFromDigitizer(handle, 4, tick2ns);
PrintChannelSettingFromDigitizer(handle, 4, ch2ns);
printf("============ Start ACQ \n");
CAEN_DGTZ_SWStartAcquisition(handle);
@ -330,15 +327,15 @@ int main(int argc, char* argv[]){
if (Nb == 0 || ret) {
return 0;
}
ret |= (CAEN_DGTZ_ErrorCode) CAEN_DGTZ_GetDPPEvents(handle, buffer, BufferSize, reinterpret_cast<void**>(&Events), DataIndex);
ret |= (CAEN_DGTZ_ErrorCode) CAEN_DGTZ_GetDPPEvents(handle, buffer, BufferSize, reinterpret_cast<void**>(&Events), EventIndex);
if (ret) {
printf("Error when getting events from data %d\n", ret);
return 0;
}
for (int ch = 0; ch < NInputCh; ch++) {
if( DataIndex[ch] > 0 ) printf("------------------------ %d, %d\n", ch, DataIndex[ch]);
for (int ev = 0; ev < DataIndex[ch]; ev++) {
for (int ch = 0; ch < NChannel; ch++) {
if( EventIndex[ch] > 0 ) printf("------------------------ %d, %d\n", ch, EventIndex[ch]);
for (int ev = 0; ev < EventIndex[ch]; ev++) {
///TrgCnt[ch]++;
if( ev == 0 ){
@ -467,14 +464,14 @@ int main(int argc, char* argv[]){
}
nw++;
}while(true);
*/
printf("=========== close Digitizer \n");
CAEN_DGTZ_SWStopAcquisition(handle);
CAEN_DGTZ_CloseDigitizer(handle);
//CAEN_DGTZ_FreeReadoutBuffer(&buffer);
//CAEN_DGTZ_FreeDPPEvents(handle, reinterpret_cast<void**>(&Events));
//CAEN_DGTZ_FreeDPPWaveforms(handle, Waveform);
CAEN_DGTZ_FreeReadoutBuffer(&buffer);
CAEN_DGTZ_FreeDPPEvents(handle, reinterpret_cast<void**>(&Events));
CAEN_DGTZ_FreeDPPWaveforms(handle, Waveform);
return 0;
}