9 #include <svd/modules/svdUnpacker/SVDUnpackerModule.h>
12 #include <framework/datastore/DataStore.h>
13 #include <framework/datastore/StoreObjPtr.h>
14 #include <framework/logging/Logger.h>
16 #include <boost/crc.hpp>
17 #define CRC16POLYREV 0x8005
19 #include <arpa/inet.h>
45 SVDUnpackerModule::SVDUnpackerModule() :
Module(),
46 m_mapping(m_xmlFileName),
48 m_FADCTriggerNumberOffset(0)
51 setDescription(
"Produce SVDShaperDigits from RawSVD. NOTE: only zero-suppressed mode is currently supported!");
58 "if >0 is the number of reported FTB header ERRORs before quiet operations. If <0 full log produced.", -1);
60 "number to be added to the FADC trigger number to match the main trigger number", 0);
64 addParam(
"silentlyAppend",
m_silentAppend,
"Append digits to a pre-existing non-empty storeArray",
bool(
false));
66 addParam(
"UnpackerErrorRate",
m_errorRate,
"Unpacker will print one error every UnpackerErrorRate",
int(1000));
67 addParam(
"PrintRawData",
m_printRaw,
"Printing Raw data words for debugging",
bool(
false));
94 B2FATAL(
"no valid SVD Channel Mapping. We stop here.");
100 B2ERROR(
"SVD xml map not loaded." << std::endl <<
101 "No SVDShaperDigit will be produced for this run!");
128 B2FATAL(
"SVDGlobalConfigParameters not valid!!");
135 #pragma GCC diagnostic push
136 #pragma GCC diagnostic ignored "-Wstack-usage="
144 B2WARNING(
"Unpacking SVDShaperDigits to a non-empty pre-existing \n"
145 <<
"StoreArray. This can lead to undesired behaviour. At least\n"
146 <<
"remember to use SVDShaperDigitSorter in your path and \n"
147 <<
"set the silentlyAppend parameter of SVDUnpacker to true.");
150 vector<SVDDAQDiagnostic*> vDiagnostic_ptr;
152 map<SVDShaperDigit, SVDDAQDiagnostic*> diagnosticMap;
154 map<unsigned short, set<pair<unsigned short, unsigned short> > > apvsByPipeline;
157 B2ERROR(
"Missing valid EventMetaData." << std::endl <<
"No SVDShaperDigit produced for this event!");
161 bool nFADCmatch =
true;
162 bool nAPVmatch =
true;
163 bool badMapping =
false;
164 bool badHeader =
false;
165 bool badTrailer =
false;
166 bool missedHeader =
false;
167 bool missedTrailer =
false;
170 bool isSetEventInfo =
false;
173 bool isSetNAPVsamples =
false;
175 unsigned short nAPVheaders = 999;
176 set<short> seenAPVHeaders = {};
178 unsigned short nEntries_rawSVD =
m_rawSVD.getEntries();
181 short fadc = 255, apv = 63;
192 for (
unsigned int i = 0; i < nEntries_rawSVD; i++) {
194 unsigned int numEntries_rawSVD =
m_rawSVD[ i ]->GetNumEntries();
195 for (
unsigned int j = 0; j < numEntries_rawSVD; j++) {
197 unsigned short nWords[4];
198 nWords[0] =
m_rawSVD[i]->Get1stDetectorNwords(j);
199 nWords[1] =
m_rawSVD[i]->Get2ndDetectorNwords(j);
200 nWords[2] =
m_rawSVD[i]->Get3rdDetectorNwords(j);
201 nWords[3] =
m_rawSVD[i]->Get4thDetectorNwords(j);
203 uint32_t* data32tab[4];
205 data32tab[0] = (uint32_t*)
m_rawSVD[i]->Get1stDetectorBuffer(j);
206 data32tab[1] = (uint32_t*)
m_rawSVD[i]->Get2ndDetectorBuffer(j);
207 data32tab[2] = (uint32_t*)
m_rawSVD[i]->Get3rdDetectorBuffer(j);
208 data32tab[3] = (uint32_t*)
m_rawSVD[i]->Get4thDetectorBuffer(j);
211 unsigned short ftbError = 0;
212 unsigned short trgType = 0;
213 unsigned short trgNumber = 0;
214 unsigned short daqMode = -1;
215 unsigned short daqType = 0;
218 unsigned short apvErrors;
219 unsigned short pipAddr;
220 unsigned short ftbFlags = 0;
221 unsigned short apvErrorsOR = 0;
223 bool is3sampleData =
false;
224 bool is6sampleData =
false;
226 for (
unsigned int buf = 0; buf < 4; buf++) {
228 if (data32tab[buf] ==
nullptr && nWords[buf] == 0)
continue;
229 if (
m_printRaw)
printB2Debug(data32tab[buf], data32tab[buf], &data32tab[buf][nWords[buf] - 1], nWords[buf]);
231 missedHeader =
false;
232 missedTrailer =
false;
234 uint32_t* data32_it = data32tab[buf];
235 short strip, sample[6];
236 vector<uint32_t> crc16vec;
238 for (; data32_it != &data32tab[buf][nWords[buf]]; data32_it++) {
248 crc16vec.push_back(*data32_it);
254 if (ftbError != 240) {
258 switch (ftbError - 240) {
260 B2ERROR(
"FADC Event Number is different from (FTB & TTD) Event Numbers");
263 B2ERROR(
"TTD Event Number is different from (FTB & FADC) Event Numbers");
266 B2ERROR(
"FTB Event Number is different from (TTD & FADC) Event Numbers");
269 B2ERROR(
"(FTB, TTD & FADC) Event Numbers are different from each other");
272 B2ERROR(
"Problem with errorsField variable in FTB Header" <<
LogVar(
"abnormal value", ftbError));
278 (eventNo & 0xFFFFFF)) {
282 B2ERROR(
"Event number mismatch detected! The event number given by EventMetaData object is different from the one in the FTB Header."
283 <<
LogVar(
"Expected event number & 0xFFFFFF",
304 if (daqType) daqMode = 3;
312 is3sampleData =
false;
313 is6sampleData =
false;
315 if (daqMode == 0) B2ERROR(
"SVDDataFormatCheck: the event " << eventNo <<
316 " is apparently taken with 1-sample mode, this is not expected.");
317 if (daqMode == 1) is3sampleData =
true;
318 if (daqMode == 2) is6sampleData =
true;
326 B2ERROR(
"Event number mismatch detected! The event number given by EventMetaData object is different from the one in the FADC Header. "
327 <<
LogVar(
"Event number", eventNo) <<
LogVar(
"FADC", fadc) <<
LogVar(
"Trigger number LSByte reported by the FADC",
336 if (!isSetEventInfo) {
347 isSetEventInfo =
true;
358 seenAPVHeaders.insert(apv);
365 if (apvErrors != 0) {
372 currentDAQDiagnostic =
m_storeDAQDiagnostics.appendNew(trgNumber, trgType, pipAddr, cmc1, cmc2, apvErrors, ftbError, nFADCmatch,
374 badHeader, missedHeader, missedTrailer,
376 vDiagnostic_ptr.push_back(currentDAQDiagnostic);
378 apvsByPipeline[pipAddr].insert(make_pair(fadc, apv));
398 if (!isSetNAPVsamples) {
400 isSetNAPVsamples =
true;
403 B2ERROR(
"DAQMode value (indicating 3-sample acquisition mode) doesn't correspond to the actual number of samples (6) in the data! The data might be corrupted!");
417 if (!isSetNAPVsamples) {
419 isSetNAPVsamples =
true;
422 B2ERROR(
"DAQMode value (indicating 6-sample acquisition mode) doesn't correspond to the actual number of samples (3) in the data! The data might be corrupted!");
428 if (newShaperDigit) {
429 diagnosticMap.insert(make_pair(*newShaperDigit, currentDAQDiagnostic));
430 delete newShaperDigit;
432 B2FATAL(
"Respective FADC/APV combination not found -->> incorrect payload in the database! ");
445 if (
APVmap->find(fadc) ==
APVmap->end()) badMapping =
true;
448 unsigned short nAPVs =
APVmap->count(fadc);
450 if (nAPVheaders == 0) {
451 currentDAQDiagnostic =
m_storeDAQDiagnostics.appendNew(0, 0, 0, 0, 0, 0, ftbError, nFADCmatch, nAPVmatch, badHeader, 0, 0, fadc, 0);
452 vDiagnostic_ptr.push_back(currentDAQDiagnostic);
455 if (nAPVs != nAPVheaders) {
457 for (
const auto& fadcApv : *
APVmap) {
458 if (fadcApv.first != fadc)
continue;
459 if (seenAPVHeaders.find(fadcApv.second) == seenAPVHeaders.end()) {
461 auto missingRec =
m_missingAPVs.find(make_pair(fadcApv.first, fadcApv.second));
464 if (missingRec->second.first > eventNo)
465 missingRec->second.first = eventNo;
466 if (missingRec->second.second < eventNo)
467 missingRec->second.second = eventNo;
472 make_pair(fadcApv.first, fadcApv.second),
473 make_pair(eventNo, eventNo)
476 int(fadcApv.second)) <<
LogVar(
"FADC",
477 int(fadcApv.first)));
484 seenAPVHeaders.clear();
487 if ((ftbFlags >> 5) != 0) badTrailer =
true;
491 B2ERROR(
" FTB Flags variable has an active error bit(s)" <<
LogVar(
"on FADC number", fadc));
493 if (ftbFlags & 16) B2ERROR(
"----> CRC error has been detected. Data might be corrupted!");
494 if (ftbFlags & 8) B2ERROR(
"----> Bad Event indication has been detected. Data might be corrupted!");
495 if (ftbFlags & 4) B2ERROR(
"----> Double Header has been detected. Data might be corrupted!");
496 if (ftbFlags & 2) B2ERROR(
"----> Time Out has been detected. Data might be corrupted!");
497 if (ftbFlags & 1) B2ERROR(
"----> Event Too Long! Data might be corrupted!");
512 unsigned short iCRC = crc16vec.size();
513 uint32_t crc16input[iCRC];
515 for (
unsigned short icrc = 0; icrc < iCRC; icrc++)
516 crc16input[icrc] = htonl(crc16vec.at(icrc));
519 boost::crc_basic<16> bcrc(0x8005, 0xffff, 0,
false,
false);
520 bcrc.process_block(crc16input, crc16input + iCRC);
521 unsigned int checkCRC = bcrc.checksum();
524 B2WARNING(
"FTB CRC16 checksum DOES NOT MATCH" <<
LogVar(
"for FADC no.", fadc));
536 if (!(
seenHeadersAndTrailers & 1)) {B2ERROR(
"Missing FTB Header is detected. SVD data might be corrupted!" <<
LogVar(
"Event number", eventNo) <<
LogVar(
"FADC", fadc)); missedHeader =
true;}
537 if (!(
seenHeadersAndTrailers & 2)) {B2ERROR(
"Missing FADC Header is detected -> related FADC number couldn't be retreived. SVD data might be corrupted! " <<
LogVar(
"Event number", eventNo) <<
LogVar(
"previous FADC", fadc)); missedHeader =
true;}
538 if (!(
seenHeadersAndTrailers & 4)) {B2ERROR(
"Missing FADC Trailer is detected. SVD data might be corrupted!" <<
LogVar(
"Event number", eventNo) <<
LogVar(
"FADC", fadc)); missedTrailer =
true;}
539 if (!(
seenHeadersAndTrailers & 8)) {B2ERROR(
"Missing FTB Trailer is detected. SVD data might be corrupted!" <<
LogVar(
"Event number", eventNo) <<
LogVar(
"FADC", fadc)); missedTrailer =
true;}
545 for (
auto p : vDiagnostic_ptr) {
547 p->setFTBFlags(ftbFlags);
548 p->setApvErrorOR(apvErrorsOR);
549 p->setAPVMatch(nAPVmatch);
550 p->setBadMapping(badMapping);
551 p->setBadTrailer(badTrailer);
552 p->setMissedHeader(missedHeader);
553 p->setMissedTrailer(missedTrailer);
557 vDiagnostic_ptr.clear();
564 auto major_apv = max_element(apvsByPipeline.begin(), apvsByPipeline.end(),
565 [](
const decltype(apvsByPipeline)::value_type & p1,
566 const decltype(apvsByPipeline)::value_type & p2) ->
bool
567 {
return p1.second.size() < p2.second.size(); }
572 p.setEmuPipelineAddress(major_apv->first);
574 if (apvsByPipeline.size() > 1)
575 for (
const auto& p : apvsByPipeline) {
576 if (p.first == major_apv->first)
continue;
577 for (
const auto& fadcApv : p.second) {
579 auto upsetRec =
m_upsetAPVs.find(make_pair(fadcApv.first, fadcApv.second));
582 if (upsetRec->second.first > eventNo)
583 upsetRec->second.first = eventNo;
584 if (upsetRec->second.second < eventNo)
585 upsetRec->second.second = eventNo;
590 make_pair(fadcApv.first, fadcApv.second),
591 make_pair(eventNo, eventNo)
595 if (pp.getFADCNumber() == fadcApv.first and pp.getAPVNumber() == fadcApv.second)
596 pp.setUpsetAPV(
true);
599 int(fadcApv.first)) <<
LogVar(
"Event number", eventNo));
606 for (
auto& p : diagnosticMap) {
608 if ((
m_killUpsetDigits && p.second->getPipelineAddress() != p.second->getEmuPipelineAddress()) || p.second->getFTBError() != 240
609 || p.second->getFTBFlags() || p.second->getAPVError() || !(p.second->getAPVMatch()) || !(p.second->getFADCMatch())
610 || p.second->getBadHeader()
611 || p.second->getBadMapping() || p.second->getUpsetAPV() || p.second->getMissedHeader() || p.second->getMissedTrailer())
continue;
621 #pragma GCC diagnostic pop
628 B2WARNING(
"SVDUnpacker summary 1: Missing APVs");
630 B2WARNING(
LogVar(
"Missing APV", miss.first.second) <<
LogVar(
"FADC", miss.first.first) <<
LogVar(
"since event",
631 miss.second.first) <<
LogVar(
"to event", miss.second.second));
634 B2WARNING(
"SVDUnpacker summary 2: Upset APVs");
636 B2WARNING(
LogVar(
"Upset APV", upst.first.second) <<
LogVar(
"FADC", upst.first.first) <<
637 LogVar(
"since event", upst.second.first) <<
LogVar(
"to event", upst.second.second));
646 uint32_t* min = std::max((data32 - nWords), data32_min);
647 uint32_t* max = std::min((data32 + nWords), data32_max);
650 std::stringstream os;
651 os << std::hex << std::setfill(
'0');
652 for (uint32_t* ptr = min; ptr <= max; ++ptr) {
653 os << std::setw(8) << *ptr;
654 if (++counter % 10 == 0) os << std::endl;
bool hasChanged()
Check whether the object has changed since the last call to hasChanged of the accessor).
bool isValid() const
isValid is always true if we have a filename
@ c_ErrorIfAlreadyRegistered
If the object/array was already registered, produce an error (aborting initialisation).
void setDescription(const std::string &description)
Sets the description of the module.
void setPropertyFlags(unsigned int propertyFlags)
Sets the flags for the module properties.
@ c_ParallelProcessingCertified
This module can be run in parallel processing mode safely (All I/O must be done through the data stor...
std::string getFileName() const
Get the name of the downloaded payload file.
Class to store SVD DAQ diagnostic information.
Class to store SVD mode information.
The SVD ShaperDigit class.
Class to store Trigger Type information.
int m_wrongFTBcrc
FTB CRC no-Match counter.
StoreArray< SVDDAQDiagnostic > m_storeDAQDiagnostics
SVDDAQDiagnostic array.
virtual ~SVDUnpackerModule()
Destructor of the module.
unsigned short seenHeadersAndTrailers
this 4-bits value should be 1111 if no headers/trailers are missing
int m_shutUpFTBError
regulates the number of "Event number mismatch" errors reported
MainHeader m_MainHeader
Implementation of FADC Header.
StoreArray< RawSVD > m_rawSVD
output for RawSVD
FADCTrailer m_FADCTrailer
Implementation of FADC Trailer.
StoreObjPtr< SVDEventInfo > m_svdEventInfoPtr
SVDEventInfo output per event.
virtual void initialize() override
Initializes the Module.
StoreArray< SVDShaperDigit > m_storeShaperDigits
SVDShaperDigit array.
virtual void event() override
event
int nAPVErrors
counter of APV errors
FTBHeader m_FTBHeader
Implementation of FTB Header.
virtual void endRun() override
end run
std::string m_rawSVDListName
RawSVD StoreArray name.
DBObjPtr< PayloadFile > m_mapping
pointer to the payload with the mapping
int nFADCMatchErrors
counter of FADC boards =/= n of RawData objects errors
bool m_killUpsetDigits
Optionally, we can kill digits coming from upset APVs right in the unpacker.
data_B m_data_B
Implementation of 2nd data word.
int m_FADCTriggerNumberOffset
FADC Trigger Offset.
std::map< std::pair< unsigned short, unsigned short >, std::pair< std::size_t, std::size_t > > m_missingAPVs
Map to store a list of missing APVs.
int nMissingAPVsErrors
counter of missing APVs errors
static std::string m_xmlFileName
XML filename.
int nEventMatchErrors
counter of Event match errors
FTBTrailer m_FTBTrailer
Implementation of FTB Trailer.
int m_errorRate
The parameter that indicates what fraction of B2ERRORs messages should be suppressed to not overload ...
APVHeader m_APVHeader
Implementation of APV Header.
int nUpsetAPVsErrors
counter of upset APV errors
void printB2Debug(uint32_t *data32, uint32_t *data32_min, uint32_t *data32_max, int nWords)
additional function that prints raw data words
virtual void beginRun() override
begin run
std::string m_svdShaperDigitListName
SVDShaperDigit StoreArray name.
std::string m_svdEventInfoName
SVDEventInfo name.
DBObjPtr< SVDGlobalConfigParameters > m_svdGlobalConfig
SVDGlobal Configuration payload.
bool m_printRaw
Optionally we can get printout of Raw Data words.
int nEventInfoMatchErrors
counter of inconsistencies in SVDEventInfo within an event
bool m_badMappingFatal
Optionally we can stop the unpacking if there is a missing APV/FADC combination in the mapping -> wro...
int nErrorFieldErrors
counter of event mismatch errors in FTB's ErrorField
data_A m_data_A
Implementation of 1st data word.
uint32_t m_data32
Input 32-bit data word.
StoreObjPtr< EventMetaData > m_eventMetaDataPtr
Required input for EventMetaData.
bool m_silentAppend
Silently append new SVDShaperDigits to a pre-existing non-empty SVDShaperDigits storeArray.
std::unordered_multimap< unsigned char, unsigned char > * APVmap
pointer to APVforFADCmap filled by mapping procedure
SVDTriggerType m_SVDTriggerType
SVDTriggerType object.
SVDModeByte m_SVDModeByte
instance of SVDModeByte for the event
std::unique_ptr< SVDOnlineToOfflineMap > m_map
Pointer to online-to-offline map.
int m_relativeTimeShift
latency difference between the 3- and 6-sample acquired events in usint of APV clock / 4,...
std::map< std::pair< unsigned short, unsigned short >, std::pair< std::size_t, std::size_t > > m_upsetAPVs
Map to store a list of upset APVs.
int nFTBFlagsErrors
counter of errors in FTBFlags variable
bool m_emulatePipelineAddress
Software emulation of pipeline address This is a replacement of hardware pipeline address emulation.
std::string m_svdDAQDiagnosticsListName
SVDDAQDiagnostic StoreArray name.
int nTriggerMatchErrors
counters for specific ERRORS produced by the Unpacker
unsigned short nFADCboards
how many FADCs we have
Class to store variables with their name which were sent to the logging service.
void addParam(const std::string &name, T ¶mVariable, const std::string &description, const T &defaultValue)
Adds a new parameter to the module.
#define REG_MODULE(moduleName)
Register the given module (without 'Module' suffix) with the framework.
Namespace to encapsulate code needed for simulation and reconstrucion of the SVD.
Abstract base class for different kinds of events.
unsigned int apvErrOR
APV Errors Field OR.
unsigned int check
MSB "1110" - for FADC Trailer identification.
unsigned int FTBFlags
FTB Flags Field.
unsigned int controlWord
MSB "ff55" - FADC Trailer ID.
unsigned int crc16
FTB CRC16 Checksum
unsigned int DAQType
(from 2020c) Event type(0): "0"…3 or …6 acquisition mode, "1"…3-mixed-6 acquisition mode
unsigned int runType
Run Type.
unsigned int FADCnum
FADC number.
unsigned int xTalk
cross talk tag
unsigned int check
MSB "110" - for FADC Header identification.
unsigned int trgNumber
Trigger Number.
unsigned int trgTiming
Trigger Timing.
unsigned int DAQMode
Event type(2:1): "00"…1-sample, "01"…3-sample, "10"…6-sample.
unsigned int trgType
Trigger Type.
unsigned int sample3
3rd data sample
unsigned int stripNum
Strip number.
unsigned int sample2
2nd data sample
unsigned int check
MSB "1" - for Data word identification.
unsigned int sample1
1st data sample
unsigned int sample6
6th data sample
unsigned int stripNum
Strip number.
unsigned int check
MSB "1" - for Data word identification.
unsigned int sample4
4th data sample
unsigned int sample5
5th data sample