GRSISort
Created by P.C. Bender
Developement Team: P.C. Bender, R. Dunlop, V. Bildstein
An extension of the ROOT analysis Framework
TGRSIDataParser.cxx
Go to the documentation of this file.
1 #include "TGRSIDataParser.h"
3 
4 #include "TChannel.h"
5 #include "Globals.h"
6 
7 #include "TScalerQueue.h"
8 
9 #include "TEpicsFrag.h"
10 #include "TParsingDiagnostics.h"
11 
12 #include "Rtypes.h"
13 
14 #include "TMidasEvent.h"
15 #include "TXMLOdb.h"
16 #include "TRunInfo.h"
17 #include "TFragment.h"
18 #include "TBadFragment.h"
19 
21  : TDataParser()
22 {
25 }
26 
28 {
29 }
30 
31 int TGRSIDataParser::Process(std::shared_ptr<TRawEvent> rawEvent)
32 {
33  std::shared_ptr<TMidasEvent> event = std::static_pointer_cast<TMidasEvent>(rawEvent);
34  int banksize;
35  void* ptr;
36  int frags = 0;
37  try {
38  switch(event->GetEventId()) {
39  case 1:
40  event->SetBankList();
41  if((banksize = event->LocateBank(nullptr, "WFDN", &ptr)) > 0) {
42  frags = TigressDataToFragment(reinterpret_cast<uint32_t*>(ptr), banksize, event);
43  } else if((banksize = event->LocateBank(nullptr, "GRF1", &ptr)) > 0) {
44  frags = ProcessGriffin(reinterpret_cast<uint32_t*>(ptr), banksize, TGRSIDataParser::EBank::kGRF1, event);
45  } else if((banksize = event->LocateBank(nullptr, "GRF2", &ptr)) > 0) {
46  frags = ProcessGriffin(reinterpret_cast<uint32_t*>(ptr), banksize, TGRSIDataParser::EBank::kGRF2, event);
47  } else if((banksize = event->LocateBank(nullptr, "GRF3", &ptr)) > 0) {
48  frags = ProcessGriffin(reinterpret_cast<uint32_t*>(ptr), banksize, TGRSIDataParser::EBank::kGRF3, event);
49  } else if((banksize = event->LocateBank(nullptr, "GRF4", &ptr)) > 0) {
50  frags = ProcessGriffin(reinterpret_cast<uint32_t*>(ptr), banksize, TGRSIDataParser::EBank::kGRF4, event);
51  } else if((banksize = event->LocateBank(nullptr, "CAEN", &ptr)) > 0) {
52  frags = CaenPsdToFragment(reinterpret_cast<uint32_t*>(ptr), banksize, event);
53  } else if((banksize = event->LocateBank(nullptr, "CPHA", &ptr)) > 0) {
54  frags = CaenPhaToFragment(reinterpret_cast<uint32_t*>(ptr), banksize, event);
55  } else if((banksize = event->LocateBank(nullptr, "MADC", &ptr)) > 0) {
56  frags = EmmaMadcDataToFragment(reinterpret_cast<uint32_t*>(ptr), banksize, event);
57  if((banksize = event->LocateBank(nullptr, "EMMT", &ptr)) > 0) {
58  //TODO: make this smarter so that an error in processing EMMT bank doesn't reduce frags
59  frags += EmmaTdcDataToFragment(reinterpret_cast<uint32_t*>(ptr), banksize, event);
60  }
61  } else if((banksize = event->LocateBank(nullptr, "EMMT", &ptr)) > 0) {
62  frags = EmmaTdcDataToFragment(reinterpret_cast<uint32_t*>(ptr), banksize, event);
63  }
64  else if(!TGRSIOptions::Get()->SuppressErrors()) {
65  std::cout<<DRED<<std::endl<<"Unknown bank in midas event #"<<event->GetSerialNumber()<<RESET_COLOR<<std::endl;
66  }
67  break;
68  case 2:
69  event->SetBankList();
70  break;
71  case 3:
72  if((banksize = event->LocateBank(nullptr, "CAEN", &ptr)) > 0) {
73  frags = CaenPsdToFragment(reinterpret_cast<uint32_t*>(ptr), banksize, event);
74  } else if((banksize = event->LocateBank(nullptr, "CPHA", &ptr)) > 0) {
75  frags = CaenPhaToFragment(reinterpret_cast<uint32_t*>(ptr), banksize, event);
76  }
77  break;
78  case 4:
79  case 5:
80  event->SetBankList();
81  if((banksize = event->LocateBank(nullptr, "MSRD", &ptr)) > 0) {
82  EPIXToScalar(reinterpret_cast<float*>(ptr), banksize, event->GetSerialNumber(), event->GetTimeStamp());
83  // EPIXToScalar will only ever read a single fragment
84  event->IncrementGoodFrags();
85  }
86  break;
87  case 0x8001:
88  // end of file ODB
89 #ifdef HAS_XML
90  TXMLOdb* odb = new TXMLOdb(event->GetData(), event->GetDataSize());
91  TRunInfo* runInfo = TRunInfo::Get();
92  TXMLNode* node = odb->FindPath("/Runinfo/Stop time binary");
93  if(node != nullptr) {
94  std::stringstream str(node->GetText());
95  unsigned int odbTime;
96  str>>odbTime;
97  odbTime *= 10; // convert from 10 ns to 1 ns units
98  if(atoi(node->GetText()) != 0 && odbTime != event->GetTimeStamp() && !TGRSIOptions::Get()->SuppressErrors()) {
99  std::cout<<"Warning, ODB stop time of last subrun ("<<odbTime<<") does not match midas time of last event in this subrun ("<<event->GetTimeStamp()<<")!"<<std::endl;
100  }
101  runInfo->SetRunStop(event->GetTimeStamp());
102  }
103  runInfo->SetRunLength();
104  delete odb;
105 #endif
106  break;
107  };
108  } catch(const std::bad_alloc&) {
109  }
110 
111  // if we failed to get any fragments and this is not a start-of-run or end-of-run event
112  // we print an error message (unless these are suppressed)
113  if(frags <= 0 && event->GetEventId() < 0x8000 && !TGRSIOptions::Get()->SuppressErrors()) {
114  event->SetBankList();
115  event->Print(Form("a%i", (-1 * frags) - 1));
116  }
117 
118  if(frags < 0) {
119  frags = 0;
120  }
121 
122  return frags;
123 }
124 
125 int TGRSIDataParser::TigressDataToFragment(uint32_t* data, int size, std::shared_ptr<TMidasEvent>& event)
126 {
127  /// Converts A MIDAS File from the Tigress DAQ into a TFragment.
128  int NumFragsFound = 0;
129  std::shared_ptr<TFragment> eventFrag = std::make_shared<TFragment>();
130  eventFrag->SetDaqTimeStamp(event->GetTimeStamp());
131  eventFrag->SetDaqId(event->GetSerialNumber());
132 
133  int x = 0;
134  uint32_t dword = *(data + x);
135 
136  uint32_t type;
137  uint32_t value;
138 
139  if(!SetTIGTriggerID(dword, eventFrag)) {
140  std::cout<<RED<<"Setting TriggerId ("<<hex(dword, 8)<<") failed on midas event: "<<DYELLOW<<event->GetSerialNumber()<<RESET_COLOR<<std::endl;
141  return -x;
142  }
143  x += 1;
144 
145  // There can be a tigger bit pattern between the header and the time ! pcb.
146 
147  if(!SetTIGTimeStamp((data + x), eventFrag)) {
148  std::cout<<RED<<x<<" Setting TimeStamp failed on midas event: "<<DYELLOW<<event->GetSerialNumber()<<RESET_COLOR<<std::endl;
149  return -x;
150  }
151  // int temp_charge = 0;
152  int temp_led = 0;
153  for(; x < size; x++) {
154  dword = *(data + x);
155  type = (dword & 0xf0000000) >> 28;
156  value = (dword & 0x0fffffff);
157  switch(type) {
158  case 0x0: // raw wave forms.
159  {
160  TChannel* chan = TChannel::GetChannel(eventFrag->GetAddress(), false);
161  if(!fNoWaveforms) {
162  SetTIGWave(value, eventFrag);
163  }
164  if((chan != nullptr) && strncmp("Tr", chan->GetName(), 2) == 0) {
165  SetTIGWave(value, eventFrag);
166  } else if((chan != nullptr) && strncmp("RF", chan->GetName(), 2) == 0) {
167  SetTIGWave(value, eventFrag);
168  }
169  } break;
170  case 0x1: // trapizodal wave forms.
171  break;
172  case 0x4: // cfd values. This also ends the the fragment!
173  SetTIGCfd(value, eventFrag);
174  SetTIGLed(temp_led, eventFrag);
175  /// check whether the fragment is 'good'
176 
177  if(((*(data + x + 1)) & 0xf0000000) != 0xe0000000) {
178  std::shared_ptr<TFragment> transferfrag = std::make_shared<TFragment>(*eventFrag);
179  eventFrag = std::make_shared<TFragment>();
180  eventFrag->SetDaqTimeStamp(transferfrag->GetDaqTimeStamp());
181  eventFrag->SetDaqId(transferfrag->GetDaqId());
182  eventFrag->SetTriggerId(transferfrag->GetTriggerId());
183  eventFrag->SetTimeStamp(transferfrag->GetTimeStamp());
184 
185  Push(fGoodOutputQueues, transferfrag);
186  NumFragsFound++;
187  event->IncrementGoodFrags();
188  } else {
189  std::shared_ptr<TFragment> transferfrag = std::make_shared<TFragment>(*eventFrag);
190  Push(fGoodOutputQueues, transferfrag);
191  NumFragsFound++;
192  event->IncrementGoodFrags();
193  eventFrag = nullptr;
194  return NumFragsFound;
195  }
196 
197  break;
198  case 0x5: // raw charge evaluation.
199  SetTIGCharge(value, eventFrag);
200  break;
201  case 0x6: temp_led = value; break;
202  case 0xb:
203  // SetTIGBitPattern
204  break;
205  case 0xc: SetTIGAddress(value, eventFrag); break;
206  case 0xe: // this ends the bank!
207  if(eventFrag) {
208  return -x;
209  }
210  break;
211  case 0xf: break;
212  default: break;
213  }
214  }
215  return NumFragsFound;
216 }
217 
218 void TGRSIDataParser::SetTIGAddress(uint32_t value, const std::shared_ptr<TFragment>& currentFrag)
219 {
220  /// Sets the digitizer address of the 'currentFrag' TFragment
221  currentFrag->SetAddress(static_cast<int32_t>(0x00ffffff & value));
222 }
223 
224 void TGRSIDataParser::SetTIGWave(uint32_t value, const std::shared_ptr<TFragment>& currentFrag)
225 {
226  /// Sets the waveform for a Tigress event.
227 
228  if(currentFrag->GetWaveform()->size() > (100000)) {
229  std::cout<<"number of wave samples found is to great"<<std::endl;
230  return;
231  }
232 
233  if((value & 0x00002000) != 0u) {
234  int temp = value & 0x00003fff;
235  temp = ~temp;
236  temp = (temp & 0x00001fff) + 1;
237  currentFrag->AddWaveformSample(static_cast<Short_t>(-temp));
238  } else {
239  currentFrag->AddWaveformSample(static_cast<Short_t>(value & 0x00001fff));
240  }
241  if(((value >> 14) & 0x00002000) != 0u) {
242  int temp = (value >> 14) & 0x00003fff;
243  temp = ~temp;
244  temp = (temp & 0x00001fff) + 1;
245  currentFrag->AddWaveformSample(static_cast<Short_t>(-temp));
246  } else {
247  currentFrag->AddWaveformSample(static_cast<Short_t>((value >> 14) & 0x00001fff));
248  }
249  return;
250 }
251 
252 void TGRSIDataParser::SetTIGCfd(uint32_t value, const std::shared_ptr<TFragment>& currentFrag)
253 {
254  /// Sets the CFD of a Tigress Event.
255 
256  currentFrag->SetCfd(int32_t(value & 0x07ffffff));
257 
258  return;
259 }
260 
261 void TGRSIDataParser::SetTIGLed(uint32_t, const std::shared_ptr<TFragment>&)
262 {
263  /// Sets the LED of a Tigress event.
264  // No longer used anywhere
265  // currentFrag->SetLed( int32_t(value & 0x07ffffff) );
266 }
267 
268 void TGRSIDataParser::SetTIGCharge(uint32_t value, const std::shared_ptr<TFragment>& currentFragment)
269 {
270  /// Sets the integrated charge of a Tigress event.
271  TChannel* chan = currentFragment->GetChannel();
272  if(chan == nullptr) {
273  chan = fChannel;
274  }
275  std::string dig_type = chan->GetDigitizerTypeString();
276 
277  int charge;
278  if((dig_type.compare(0, 5, "Tig10") == 0) || (dig_type.compare(0, 5, "TIG10") == 0)) {
279  if((value & 0x02000000) != 0u) {
280  charge = (-((~(static_cast<int32_t>(value) & 0x01ffffff)) & 0x01ffffff) + 1);
281  } else {
282  charge = (value & 0x03ffffff);
283  }
284  } else if((dig_type.compare(0, 5, "Tig64") == 0) || (dig_type.compare(0, 5, "TIG64") == 0)) {
285  if((value & 0x00200000) != 0u) {
286  charge = (-((~(static_cast<int32_t>(value) & 0x001fffff)) & 0x001fffff) + 1);
287  } else {
288  charge = ((value & 0x003fffff));
289  }
290  } else {
291  if((value & 0x02000000) != 0u) {
292  charge = (-((~(static_cast<int32_t>(value) & 0x01ffffff)) & 0x01ffffff) + 1);
293  } else {
294  charge = ((static_cast<int32_t>(value) & 0x03ffffff));
295  }
296  }
297  currentFragment->SetCharge(charge);
298 }
299 
300 bool TGRSIDataParser::SetTIGTriggerID(uint32_t value, const std::shared_ptr<TFragment>& currentFrag)
301 {
302  /// Sets the Trigger ID of a Tigress event.
303  if((value & 0xf0000000) != 0x80000000) {
304  return false;
305  }
306  value = value & 0x0fffffff;
307  unsigned int LastTriggerIdHiBits = fLastTriggerId & 0xFF000000; // highest 8 bits, remainder will be
308  unsigned int LastTriggerIdLoBits = fLastTriggerId & 0x00FFFFFF; // determined by the reported value
309  if(value < fMaxTriggerId / 10) { // the trigger id has wrapped around
310  if(LastTriggerIdLoBits > fMaxTriggerId * 9 / 10) {
311  currentFrag->SetTriggerId((uint64_t)(LastTriggerIdHiBits + value + fMaxTriggerId));
312  std::cout<<DBLUE<<"We are looping new trigger id = "<<currentFrag->GetTriggerId()<<", last trigger hi bits = "<<LastTriggerIdHiBits<<", last trigger lo bits = "<<LastTriggerIdLoBits<<", value = "<<value<<RESET_COLOR<<std::endl;
313  } else {
314  currentFrag->SetTriggerId(static_cast<uint64_t>(LastTriggerIdHiBits + value));
315  }
316  } else if(value < fMaxTriggerId * 9 / 10) {
317  currentFrag->SetTriggerId(static_cast<uint64_t>(LastTriggerIdHiBits + value));
318  } else {
319  if(LastTriggerIdLoBits < fMaxTriggerId / 10) {
320  currentFrag->SetTriggerId((uint64_t)(LastTriggerIdHiBits + value - fMaxTriggerId));
321  std::cout<<DRED<<"We are backwards looping new trigger id = "<<currentFrag->GetTriggerId()<<", last trigger hi bits = "<<LastTriggerIdHiBits<<", last trigger lo bits = "<<LastTriggerIdLoBits<<", value = "<<value<<RESET_COLOR<<std::endl;
322  } else {
323  currentFrag->SetTriggerId(static_cast<uint64_t>(LastTriggerIdHiBits + value));
324  }
325  }
326  // fragment_id_map[value]++;
327  // currentFrag->FragmentId = fragment_id_map[value];
328  fLastTriggerId = static_cast<unsigned long>(currentFrag->GetTriggerId());
329  return true;
330 }
331 
332 bool TGRSIDataParser::SetTIGTimeStamp(uint32_t* data, const std::shared_ptr<TFragment>& currentFrag)
333 {
334  /// Sets the Timestamp of a Tigress Event
335  for(int x = 0; x < 10; x++) { // finds the timestamp.
336  data = data + 1;
337  if(((*data) >> 28) == 0xa) {
338  break;
339  }
340  }
341  long timestamplow = -1;
342  long timestamphigh = -1;
343 
344 
345  if(!((*data & 0xf0000000) == 0xa0000000)) {
346  std::cout<<"here 0?\t"<<hex(*data,8)<<std::endl;
347  return false;
348  }
349 
350  unsigned int time[5] = {0}; // tigress can report up to 5 valid timestamp words
351  int x = 0;
352 
353  while((*(data + x) & 0xf0000000) == 0xa0000000) {
354  time[x] = *(data + x);
355  x += 1;
356  if(x == 5) {
357  break;
358  }
359  }
360 
361  switch(x) {
362  case 1: // bad.
363  break;
364  case 2: // minimum number of good a's
365  if(time[0] != time[1]) { // tig64's only have two, both second hex's are 0s. also some times tig10s.
366  timestamplow = time[0] & 0x00ffffff;
367  timestamphigh = time[1] & 0x00ffffff;
368  // return true;
369  }
370  break;
371  case 3:
372  if(time[0] == time[1] && time[0] != time[2]) {
373  if(((time[0] & 0x0f000000) != 0x00000000) && ((time[2] & 0x0f000000) != 0x01000000)) {
374  break;
375  }
376  timestamplow = time[0] & 0x00ffffff;
377  timestamphigh = time[2] & 0x00ffffff;
378  } else if(time[0] != time[1] && time[1] == time[2]) {
379  if(((time[0] & 0x0f000000) != 0x00000000) && ((time[1] & 0x0f000000) != 0x01000000)) {
380  break;
381  }
382  timestamplow = time[0] & 0x00ffffff;
383  timestamphigh = time[1] & 0x00ffffff;
384  } else { // assume the third if the counter.
385  // if( ((time[0]&0x0f000000)!=0x00000000) && ((time[1]&0x0f000000)!=0x01000000) )
386  // break;
387  timestamplow = time[0] & 0x00ffffff;
388  timestamphigh = time[1] & 0x00ffffff;
389  }
390  break;
391  // return true;
392  case 4:
393  case 5:
394  if(time[0] == time[1] && time[2] == time[3]) {
395  if(((time[0] & 0x0f000000) != 0x00000000) && ((time[2] & 0x0f000000) != 0x01000000)) {
396  break;
397  }
398  timestamplow = time[0] & 0x00ffffff;
399  timestamphigh = time[1] & 0x00ffffff;
400  } else {
401  if(((time[0] & 0x0f000000) != 0x00000000) && ((time[1] & 0x0f000000) != 0x01000000)) {
402  break;
403  }
404  timestamplow = time[0] & 0x00ffffff;
405  timestamphigh = time[1] & 0x00ffffff;
406  }
407  break;
408  // return true;
409  };
410  if(timestamplow > -1 && timestamphigh > -1) {
411  // combine low and high time stamp bits
412  currentFrag->SetTimeStamp((timestamphigh<<24) + timestamplow);
413  return true;
414  }
415 
416  return false;
417 }
418 
419 /////////////***************************************************************/////////////
420 /////////////***************************************************************/////////////
421 /////////////***************************************************************/////////////
422 /////////////***************************************************************/////////////
423 /////////////***************************************************************/////////////
424 /////////////***************************************************************/////////////
425 
426 int TGRSIDataParser::ProcessGriffin(uint32_t* data, const int& size, const EBank& bank, std::shared_ptr<TMidasEvent>& event)
427 {
428  // loop over words in event to find fragment header
429  int totalFrags = 0;
430  for(int index = 0; index < size;) {
431  if(((data[index]) & 0xf0000000) == 0x80000000) {
432  // if we found a fragment header we use GriffinDataToFragment which returns the number of words read
433  int words;
434  try {
435  words = GriffinDataToFragment(&data[index], size - index, bank, event->GetSerialNumber(), event->GetTimeStamp());
436  } catch(TGRSIDataParserException& e) {
437  words = -e.GetFailedWord();
438  if(!TGRSIOptions::Get()->SuppressErrors()) {
439  if(!TGRSIOptions::Get()->LogErrors()) {
440  std::cout<<std::endl<<e.what();
441  }
442  }
443  }
444  if(words > 0) {
445  // we successfully read one event with <words> words, so we advance the index by words
446  event->IncrementGoodFrags();
447  ++totalFrags;
448  index += words;
449  } else {
450  // we failed to read the fragment on word <-words>, so advance the index by -words and we create an error
451  // message
452  ++totalFrags; // if the midas bank fails, we assume it only had one frag in it... this is just used for a
453  // print statement.
454  index -= words;
455 
456  if(!TGRSIOptions::Get()->SuppressErrors()) {
457  if(!TGRSIOptions::Get()->LogErrors()) {
458  std::cout<<DRED<<"//**********************************************//"<<RESET_COLOR<<std::endl;
459  std::cout<<DRED<<"Bad things are happening. Failed on datum "<<index<<RESET_COLOR<<std::endl;
460  event->Print(Form("a%i", index));
461  std::cout<<DRED<<"//**********************************************//"<<RESET_COLOR<<std::endl;
462  } else {
463  std::string errfilename = "error.log";
464  // if(mFile) {
465  // if(mFile->GetSubRunNumber() != -1) {
466  // errfilename.append(Form("error%05i_%03i.log",mFile->GetRunNumber(),mFile->GetSubRunNumber()));
467  // } else {
468  // errfilename.append(Form("error%05i.log",mFile->GetRunNumber()));
469  // }
470  // } else {
471  // errfilename.append("error_log.log");
472  // }
473  FILE* originalstdout = stdout;
474  FILE* errfileptr = freopen(errfilename.c_str(), "a", stdout);
475  std::cout<<"//**********************************************//"<<std::endl;
476  event->Print("a");
477  std::cout<<"//**********************************************//"<<std::endl;
478  fclose(errfileptr);
479  stdout = originalstdout;
480  }
481  }
482  }
483  } else {
484  // this is not a fragment header, so we advance the index
485  ++index;
486  }
487  }
488 
489  return totalFrags;
490 }
491 
492 int TGRSIDataParser::GriffinDataToFragment(uint32_t* data, int size, EBank bank, unsigned int midasSerialNumber,
493  time_t midasTime)
494 {
495  /// Converts a Griffin flavoured MIDAS file into a TFragment and returns the number of words processed (or the
496  /// negative index of the word it failed on)
497  std::shared_ptr<TFragment> eventFrag = std::make_shared<TFragment>();
498  // no need to delete eventFrag, it's a shared_ptr and gets deleted when it goes out of scope
499  fFragmentHasWaveform = false;
501  int failedWord = -1; // Variable stores which word we failed on (if we fail). This is somewhat duplicate information
502  // to fState, but makes things easier to track.
503  bool multipleErrors = false; // Variable to store if multiple errors occured parsing one fragment
504 
505  if(fOptions == nullptr) {
507  }
508 
509  int x = 0;
510  if(!SetGRIFHeader(data[x++], eventFrag, bank)) {
511  std::cout<<DYELLOW<<"data[0] = "<<hex(data,8)<<RESET_COLOR<<std::endl;
512  // we failed to get a good header, so we don't know which detector type this fragment would've belonged to
514  // this is the first word, so no need to check is the state/failed word has been set before
516  failedWord = 0;
517  }
518 
519  eventFrag->SetDaqTimeStamp(midasTime);
520  eventFrag->SetDaqId(midasSerialNumber);
521 
522  // Changed on 11 Aug 2015 by RD to include PPG events. If the event has ModuleType 4 and address 0xffff, it is a PPG
523  // event.
524  if((eventFrag->GetModuleType() == 1 || eventFrag->GetModuleType() == 4) && eventFrag->GetAddress() == 0xffff) {
525  return GriffinDataToPPGEvent(data, size, midasSerialNumber, midasTime);
526  }
527  // If the event has detector type 15 (0xf) it's a scaler event.
528  if(eventFrag->GetDetectorType() == 0xf) {
529  // a scaler event (trigger or deadtime) has 8 words (including header and trailer), make sure we have at least
530  // that much left
531  TChannel* chan = TChannel::GetChannel(eventFrag->GetAddress(), false);
532  if((chan != nullptr) && strncmp("RF", chan->GetName(), 2) == 0){
533  //JW: RF event, stored as a scaler containing fit paramters
534  //in recent (2019 and later) GRIF-16 firmware revisions.
535  //These should be still be treated as RF event fragments, but
536  //need to be parsed differently.
537  //std::cout << "RF scaler event" << std::endl;
538  return RFScalerToFragment(data, size, eventFrag);
539  }
540  if(size < 8) {
543  failedWord = x;
544  } else {
545  multipleErrors = true;
546  }
547  throw TGRSIDataParserException(fState, failedWord, multipleErrors);
548  }
549  return GriffinDataToScalerEvent(data, eventFrag->GetAddress());
550  }
551 
552  // If the flag is set, skip any fragment without a channel
553  if(fIgnoreMissingChannel && eventFrag->GetChannel() != nullptr) {
554  // find end of this event
555  for(; x < size; x++) {
556  if((data[x] >> 28) == 0xe) return x;
557  }
558  }
559 
560  // The Network packet number is for debugging and is not always written to the midas file.
561  if(SetGRIFNetworkPacket(data[x], eventFrag)) {
562  ++x;
563  }
564 
565  // The Primary Filter Pattern is in an unstable state right now and is not
566  // always written to the midas file
567  if(SetGRIFPrimaryFilterPattern(data[x], eventFrag, bank)) {
568  ++x;
569  }
570 
571  // We can get multiple filter ids (one fragment can pass multiple filter conditions)
572  // so we have to loop until we don't find one
573  while(SetGRIFPrimaryFilterId(data[x], eventFrag)) {
574  ++x;
575  }
576 
577  // The channel trigger ID is in an unstable state right now and is not
578  // always written to the midas file
579  if(!SetGRIFChannelTriggerId(data[x++], eventFrag)) {
580  TParsingDiagnostics::Get()->BadFragment(eventFrag->GetDetectorType());
583  failedWord = x - 1; // -1 compensates the incrementation in the if-statement
584  } else {
585  multipleErrors = true;
586  }
587  }
588 
589  // The Network packet number is for debugging and is not always written to
590  // the midas file.
591  if(SetGRIFNetworkPacket(data[x], eventFrag)) {
592  x++;
593  }
594 
595  if(!SetGRIFTimeStampLow(data[x++], eventFrag)) {
596  TParsingDiagnostics::Get()->BadFragment(eventFrag->GetDetectorType());
599  failedWord = x - 1; // -1 compensates the incrementation in the if-statement
600  } else {
601  multipleErrors = true;
602  }
603  }
604 
605  if(!SetGRIFDeadTime(data[x++], eventFrag)) {
606  TParsingDiagnostics::Get()->BadFragment(eventFrag->GetDetectorType());
609  failedWord = x - 1; // -1 compensates the incrementation in the if-statement
610  } else {
611  multipleErrors = true;
612  }
613  }
614 
615  std::vector<Int_t> tmpCharge;
616  std::vector<Short_t> tmpIntLength;
617  std::vector<Int_t> tmpCfd;
618 
619  for(; x < size; x++) {
620  uint32_t dword = data[x];
621  uint32_t packet = dword >> 28;
622  uint32_t value = dword & 0x0fffffff;
623 
624  switch(packet) {
625  case 0x8: // The 8 packet type is for event headers
626  // if this happens, we have "accidentally" found another event.
627  // currently the GRIF-C only sets the primary/secondary port of the address for the first header (of the corrupt
628  // event)
629  // so we want to ignore this corrupt event and the next event which has a wrong address
630  TParsingDiagnostics::Get()->BadFragment(eventFrag->GetDetectorType());
633  failedWord = x + 1; //+1 to ensure we don't read this header as start of a good event
634  } else {
635  multipleErrors = true;
636  }
637  Push(*fBadOutputQueue, std::make_shared<TBadFragment>(*eventFrag, data, size, failedWord, multipleErrors));
638  throw TGRSIDataParserException(fState, failedWord, multipleErrors);
639  break;
640  case 0xc: // The c packet type is for waveforms
641  if(!fNoWaveforms) {
642  SetGRIFWaveForm(value, eventFrag);
643  }
644  break;
645  case 0xd:
646  SetGRIFNetworkPacket(dword, eventFrag); // The network packet placement is not yet stable.
647  break;
648  case 0xe:
649  // changed on 21 Apr 2015 by JKS, when signal processing code from Chris changed the trailer.
650  // change should be backward-compatible
651  if((value & 0x3fff) == (eventFrag->GetChannelId() & 0x3fff)) {
652  if(!fOptions->SuppressErrors() && (eventFrag->GetModuleType() == 2) && (bank < EBank::kGRF3)) {
653  // check whether the nios finished and if so whether it finished with an error
654  if(((value >> 14) & 0x1) == 0x1) {
655  if(((value >> 16) & 0xff) != 0) {
656  std::cout<<BLUE<<hex(eventFrag->GetAddress(),4)<<": NIOS code finished with error "<<hex((value >> 16) & 0xff,2)<<RESET_COLOR<<std::endl;
657  }
658  }
659  }
660 
661  if((eventFrag->GetModuleType() == 1) || (bank > EBank::kGRF2)) { // 4Gs have this only for banks newer than GRF2
662  eventFrag->SetAcceptedChannelId((value >> 14) & 0x3fff);
663  } else {
664  eventFrag->SetAcceptedChannelId(0);
665  }
666 
667  // check the number of words the header said we should have with the number of words we've read
668  // the number of words is only set for bank >= GRF3
669  // if the fragment has a waveform, we can't compare the number of words
670  // the headers number of words includes the header (word 0) itself, so we need to compare to x plus one
671  if(fOptions->WordOffset() >= 0 && eventFrag->GetNumberOfWords() > 0 && !eventFrag->HasWave() && eventFrag->GetNumberOfWords() != x + fOptions->WordOffset()) {
674  failedWord = x;
675  } else {
676  multipleErrors = true;
677  }
678  Push(*fBadOutputQueue, std::make_shared<TBadFragment>(*eventFrag, data, size, failedWord, multipleErrors));
679  throw TGRSIDataParserException(fState, failedWord, multipleErrors);
680  }
681 
682  // the way we insert the fragment(s) depends on the module type and bank:
683  // 1 - for module type 1 & bank GRF4, we can't insert the fragments yet, we need to put them in a separate queue
684  // 2 - for module type 2 (4G, all banks) and module type 1 & bank GRF3 we set the single charge, cfd, and
685  // IntLength, and insert the fragment
686  // 3 - for module type 1 & banks GRF1/GRF2 we loop over the charge, cfd, and IntLengths, and insert the
687  // (multiple) fragment(s)
688  // the last two cases can be treated the same since the second case will just have a single length charge,
689  // cfd, and IntLengths
690 
691  // so we only need to check for the first case
692  if(eventFrag->GetModuleType() == 1 && bank == EBank::kGRF4) {
693  if(tmpCfd.size() != 1) {
694  if(fRecordDiag) {
695  TParsingDiagnostics::Get()->BadFragment(eventFrag->GetDetectorType());
696  }
699  failedWord = x;
700  } else {
701  multipleErrors = true;
702  }
703  Push(*fBadOutputQueue, std::make_shared<TBadFragment>(*eventFrag, data, size, failedWord, multipleErrors));
704  throw TGRSIDataParserException(fState, failedWord, multipleErrors);
705  }
706  eventFrag->SetCfd(tmpCfd[0]);
707  if(fRecordDiag) {
708  TParsingDiagnostics::Get()->GoodFragment(eventFrag->GetDetectorType());
709  }
710  fFragmentMap.Add(eventFrag, tmpCharge, tmpIntLength);
711  return x;
712  }
713  if(tmpCharge.size() != tmpIntLength.size() || tmpCharge.size() != tmpCfd.size()) {
714  if(fRecordDiag) {
715  TParsingDiagnostics::Get()->BadFragment(eventFrag->GetDetectorType());
716  }
719  failedWord = x;
720  } else {
721  multipleErrors = true;
722  }
723  Push(*fBadOutputQueue, std::make_shared<TBadFragment>(*eventFrag, data, size, failedWord, multipleErrors));
724  throw TGRSIDataParserException(fState, failedWord, multipleErrors);
725  }
726  for(size_t h = 0; h < tmpCharge.size(); ++h) {
727  eventFrag->SetCharge(tmpCharge[h]);
728  eventFrag->SetKValue(tmpIntLength[h]);
729  eventFrag->SetCfd(tmpCfd[h]);
730  if(fRecordDiag) {
731  TParsingDiagnostics::Get()->GoodFragment(eventFrag->GetDetectorType());
732  }
735  fLastTimeStampMap[eventFrag->GetAddress()] = eventFrag->GetTimeStamp();
736  }
737  Push(fGoodOutputQueues, std::make_shared<TFragment>(*eventFrag));
738  } else {
739  if(fOptions->ReconstructTimeStamp() && fState == EDataParserState::kBadHighTS && !multipleErrors) {
740  // std::cout<<"reconstructing timestamp from 0x"<<std::hex<<eventFrag->GetTimeStamp()<<" using
741  // 0x"<<fLastTimeStampMap[eventFrag->GetAddress()];
742  // reconstruct the high bits of the timestamp from the high bits of the last time stamp of the
743  // same address after converting the saved timestamp back to 10 ns units
744  if((eventFrag->GetTimeStamp() & 0x0fffffff) <
745  (fLastTimeStampMap[eventFrag->GetAddress()] & 0x0fffffff)) {
746  // we had a wrap-around of the low time stamp, so we need to set the high bits to the old
747  // high bits plus one
748  eventFrag->AppendTimeStamp(((fLastTimeStampMap[eventFrag->GetAddress()] >> 28) + 1)<<28);
749  } else {
750  eventFrag->AppendTimeStamp(fLastTimeStampMap[eventFrag->GetAddress()] & 0x3fff0000000);
751  }
752  // std::cout<<" => 0x"<<eventFrag->GetTimeStamp()<<std::dec<<std::endl;
753  Push(fGoodOutputQueues, std::make_shared<TFragment>(*eventFrag));
754  } else {
755  // std::cout<<"Can't reconstruct time stamp, "<<fOptions->ReconstructTimeStamp()<<",
756  // state "<<fState<<" = "<<EDataParserState::kBadHighTS<<", "<<multipleErrors<<std::endl;
757  Push(*fBadOutputQueue, std::make_shared<TBadFragment>(*eventFrag, data, size, failedWord, multipleErrors));
758  }
759  }
760  }
761  return x;
762  } else {
763  if(fRecordDiag) {
764  TParsingDiagnostics::Get()->BadFragment(eventFrag->GetDetectorType());
765  }
768  failedWord = x;
769  } else {
770  multipleErrors = true;
771  }
772  Push(*fBadOutputQueue, std::make_shared<TBadFragment>(*eventFrag, data, size, failedWord, multipleErrors));
773  throw TGRSIDataParserException(fState, failedWord, multipleErrors);
774  }
775  break;
776  case 0xf:
777  switch(bank) {
778  case EBank::kGRF1: // format from before May 2015 experiments
779  TParsingDiagnostics::Get()->BadFragment(eventFrag->GetDetectorType());
782  failedWord = x;
783  } else {
784  multipleErrors = true;
785  }
786  Push(*fBadOutputQueue, std::make_shared<TBadFragment>(*eventFrag, data, size, failedWord, multipleErrors));
787  throw TGRSIDataParserException(fState, failedWord, multipleErrors);
788  break;
789  case EBank::kGRF2: // from May 2015 to the end of 2015 0xf denoted a psd-word from a 4G
790  if(x + 1 < size) {
791  SetGRIFCc(value, eventFrag);
792  ++x;
793  dword = data[x];
794  SetGRIFPsd(dword, eventFrag);
795  } else {
796  TParsingDiagnostics::Get()->BadFragment(eventFrag->GetDetectorType());
799  failedWord = x;
800  } else {
801  multipleErrors = true;
802  }
803  Push(*fBadOutputQueue, std::make_shared<TBadFragment>(*eventFrag, data, size, failedWord, multipleErrors));
804  throw TGRSIDataParserException(fState, failedWord, multipleErrors);
805  }
806  break;
807  case EBank::kGRF3: // from 2016 on we're back to reserving 0xf for faults
808  case EBank::kGRF4:
809  TParsingDiagnostics::Get()->BadFragment(eventFrag->GetDetectorType());
812  failedWord = x;
813  } else {
814  multipleErrors = true;
815  }
816  Push(*fBadOutputQueue, std::make_shared<TBadFragment>(*eventFrag, data, size, failedWord, multipleErrors));
817  throw TGRSIDataParserException(fState, failedWord, multipleErrors);
818  break;
819  default:
820  std::cout<<"This bank not yet defined."<<std::endl;
821  break;
822  }
823  break;
824 
825  default:
826  // these are charge/cfd words which are different depending on module type, and bank number/detector type
827  switch(eventFrag->GetModuleType()) {
828  case 1:
829  switch(bank) { // the GRIF-16 data format depends on the bank number
830  case EBank::kGRF1: // bank's 1&2 have n*2 words with (5 high bits IntLength, 26 Charge)(5 low bits IntLength, 26
831  // Cfd)
832  case EBank::kGRF2:
833  // read this pair of charge/cfd words, check if the next word is also a charge/cfd word
834  if(((data[x] & 0x80000000) == 0x0) && x + 1 < size && (data[x + 1] & 0x80000000) == 0x0) {
835  Short_t tmp = (data[x] & 0x7c000000) >> 21; // 21 = 26 minus space for 5 low bits
836  tmpCharge.push_back((data[x] & 0x03ffffff) | (((data[x] & 0x02000000) == 0x02000000)
837  ? 0xfc000000
838  : 0x0)); // extend the sign bit of 26bit charge word
839  ++x;
840  tmpIntLength.push_back(tmp | ((data[x] & 0x7c000000) >> 26));
841  tmpCfd.push_back(data[x] & 0x03ffffff);
842  } else {
843  TParsingDiagnostics::Get()->BadFragment(eventFrag->GetDetectorType());
846  failedWord = x;
847  } else {
848  multipleErrors = true;
849  }
850  Push(*fBadOutputQueue, std::make_shared<TBadFragment>(*eventFrag, data, size, failedWord, multipleErrors));
851  throw TGRSIDataParserException(fState, failedWord, multipleErrors);
852  }
853  break;
854  case EBank::kGRF3: // bank 3 has 2 words with (5 high bits IntLength, 26 Charge)(9 low bits IntLength, 22 Cfd)
855  if(x + 1 < size &&
856  (data[x + 1] & 0x80000000) == 0x0) { // check if the next word is also a charge/cfd word
857  Short_t tmp = (data[x] & 0x7c000000) >> 17; // 17 = 26 minus space for 9 low bits
858  tmpCharge.push_back((data[x] & 0x03ffffff) | (((data[x] & 0x02000000) == 0x02000000)
859  ? 0xfc000000
860  : 0x0)); // extend the sign bit of 26bit charge word
861  ++x;
862  tmpIntLength.push_back(tmp | ((data[x] & 0x7fc00000) >> 22));
863  tmpCfd.push_back(data[x] & 0x003fffff);
864  break;
865  } else {
866  TParsingDiagnostics::Get()->BadFragment(eventFrag->GetDetectorType());
869  failedWord = x;
870  } else {
871  multipleErrors = true;
872  }
873  Push(*fBadOutputQueue, std::make_shared<TBadFragment>(*eventFrag, data, size, failedWord, multipleErrors));
874  throw TGRSIDataParserException(fState, failedWord, multipleErrors);
875  }
876  break;
877  case EBank::kGRF4: // bank 4 can have more than one integration (up to four), but these have to be combined with
878  // other fragments/hits!
879  // we always have 2 words with (5 high bits IntLength, 26 Charge)(9 low bits IntLength, 22 Cfd)
880  if((data[x] & 0x80000000) == 0x0 && x + 1 < size &&
881  (data[x + 1] & 0x80000000) == 0x0) { // check if the next word is also a charge/cfd word
882  Short_t tmp = ((data[x] & 0x7c000000) >> 17) |
883  (((data[x] & 0x40000000) == 0x40000000) ? 0xc000 : 0x0); // 17 = 26 minus space for 9
884  // low bits; signed, so we
885  // extend the sign bit from 14
886  // (31) to 16 bits
887  if(false && (data[x] & 0x02000000) == 0x02000000) { // overflow bit was set - disabled VB
888  tmpCharge.push_back(std::numeric_limits<int>::max());
889  } else {
890  tmpCharge.push_back((data[x] & 0x01ffffff) |
891  (((data[x] & 0x01000000) == 0x01000000)
892  ? 0xfe000000
893  : 0x0)); // extend the sign bit of 25bit charge word
894  }
895  ++x;
896  tmpIntLength.push_back(tmp | ((data[x] & 0x7fc00000) >> 22));
897  tmpCfd.push_back(data[x] & 0x003fffff);
898  // check if we have two more words (X & XI) with (8 num hits, 2 reserved, 14 IntLength2)(31 Charge2);
899  // x has already been incremented once!
900  if(x + 2 < size && (data[x + 1] & 0x80000000) == 0x0 && (data[x + 2] & 0x80000000) == 0x0) {
901  ++x;
902  tmpIntLength.push_back((data[x] & 0x3fff) | (((data[x] & 0x2000) == 0x2000) ? 0xc000 : 0x0));
903  // eventFrag->SetNumberOfPileups((data[x] >> 16) & 0xff);
904  ++x;
905  if((data[x] & 0x02000000) == 0x02000000) { // overflow bit was set
906  tmpCharge.push_back(std::numeric_limits<int>::max());
907  } else {
908  tmpCharge.push_back((data[x] & 0x01ffffff) |
909  (((data[x] & 0x01000000) == 0x01000000)
910  ? 0xfe000000
911  : 0x0)); // extend the sign bit of 25bit charge word
912  }
913  // check if we have two more words (XI & XIII) with (14 IntLength4, 2 reserved, 14 IntLength3)(31
914  // Charge3); x has already been incremented thrice!
915  if(x + 2 < size && (data[x + 1] & 0x80000000) == 0x0 && (data[x + 2] & 0x80000000) == 0x0) {
916  ++x;
917  tmpIntLength.push_back((data[x] & 0x3fff) | (((data[x] & 0x2000) == 0x2000) ? 0xc000 : 0x0));
918  tmpIntLength.push_back((data[x] >> 16) |
919  (((data[x] & 0x20000000) == 0x20000000) ? 0xc000 : 0x0));
920  ++x;
921  if((data[x] & 0x02000000) == 0x02000000) { // overflow bit was set
922  tmpCharge.push_back(std::numeric_limits<int>::max());
923  } else {
924  tmpCharge.push_back((data[x] & 0x01ffffff) |
925  (((data[x] & 0x01000000) == 0x01000000)
926  ? 0xfe000000
927  : 0x0)); // extend the sign bit of 25bit charge word
928  }
929  // check if we have one final word with (31 Charge4), otherwise remove the last integration
930  // length (IntLength4)
931  if(x + 1 < size && (data[x + 1] & 0x80000000) == 0x0) {
932  ++x;
933  if((data[x] & 0x02000000) == 0x02000000) { // overflow bit was set
934  tmpCharge.push_back(std::numeric_limits<int>::max());
935  } else {
936  tmpCharge.push_back((data[x] & 0x01ffffff) |
937  (((data[x] & 0x01000000) == 0x01000000)
938  ? 0xfe000000
939  : 0x0)); // extend the sign bit of 25bit charge word
940  }
941  } else {
942  tmpIntLength.pop_back();
943  }
944  } else if((data[x + 1] & 0x80000000) == 0x0) { // 5 words
945  ++x;
946  }
947  } else if((data[x + 1] & 0x80000000) == 0x0) { // 3 words
948  ++x;
949  }
950  } else {
951  // these types of corrupt events quite often end without a trailer which leads to the header of the
952  // next event missing the primary/secondary part of the address
953  // so we look for the next trailer and stop there
954  while(x < size && (data[x] & 0xf0000000) != 0xe0000000) {
955  ++x;
956  }
957  TParsingDiagnostics::Get()->BadFragment(eventFrag->GetDetectorType());
960  failedWord = x;
961  } else {
962  multipleErrors = true;
963  }
964  Push(*fBadOutputQueue, std::make_shared<TBadFragment>(*eventFrag, data, size, failedWord, multipleErrors));
965  throw TGRSIDataParserException(fState, failedWord, multipleErrors);
966  }
967  break;
968  default:
969  if(!fOptions->SuppressErrors()) {
970  std::cout<<DRED<<"Error, bank type "<<static_cast<std::underlying_type<EBank>::type>(bank)<<" not implemented yet"<<RESET_COLOR<<std::endl;
971  }
972  TParsingDiagnostics::Get()->BadFragment(eventFrag->GetDetectorType());
975  failedWord = x;
976  } else {
977  multipleErrors = true;
978  }
979  Push(*fBadOutputQueue, std::make_shared<TBadFragment>(*eventFrag, data, size, failedWord, multipleErrors));
980  throw TGRSIDataParserException(fState, failedWord, multipleErrors);
981  break;
982  }
983  break;
984  case 2:
985  // the 4G data format depends on the detector type, but the first two words are always the same
986  if(x + 1 < size && (data[x + 1] & 0x80000000) == 0x0) { // check if the next word is also a charge/cfd word
987  Short_t tmp = (data[x] & 0x7c000000) >> 21; // 21 = 26 minus space for 5 low bits
988  tmpCharge.push_back((data[x] & 0x03ffffff) | (((data[x] & 0x02000000) == 0x02000000)
989  ? 0xfc000000
990  : 0x0)); // extend the sign bit of 26bit charge word
991  ++x;
992  tmpIntLength.push_back(tmp | ((data[x] & 0x7c000000) >> 26));
993  tmpCfd.push_back(data[x] & 0x03ffffff);
994  } else {
995  TParsingDiagnostics::Get()->BadFragment(eventFrag->GetDetectorType());
998  failedWord = x;
999  } else {
1000  multipleErrors = true;
1001  }
1002  Push(*fBadOutputQueue, std::make_shared<TBadFragment>(*eventFrag, data, size, failedWord, multipleErrors));
1003  throw TGRSIDataParserException(fState, failedWord, multipleErrors);
1004  }
1005  // for descant types (6,10,11) there are two more words for banks > GRF2 (bank GRF2 used 0xf packet and bank
1006  // GRF1 never had descant)
1007  if(bank > EBank::kGRF2 && (eventFrag->GetDetectorType() == 6 || eventFrag->GetDetectorType() == 10 ||
1008  eventFrag->GetDetectorType() == 11)) {
1009  ++x;
1010  if(x + 1 < size && (data[x + 1] & 0x80000000) == 0x0) {
1011  SetGRIFCc(value, eventFrag);
1012  ++x;
1013  dword = data[x];
1014  SetGRIFPsd(dword, eventFrag);
1015  } else {
1016  TParsingDiagnostics::Get()->BadFragment(eventFrag->GetDetectorType());
1019  failedWord = x;
1020  } else {
1021  multipleErrors = true;
1022  }
1023  Push(*fBadOutputQueue, std::make_shared<TBadFragment>(*eventFrag, data, size, failedWord, multipleErrors));
1024  throw TGRSIDataParserException(fState, failedWord, multipleErrors);
1025  }
1026  }
1027  break;
1028  default:
1029  if(!fOptions->SuppressErrors()) {
1030  std::cout<<DRED<<"Error, module type "<<eventFrag->GetModuleType()<<" not implemented yet"<<RESET_COLOR<<std::endl;
1031  }
1032  TParsingDiagnostics::Get()->BadFragment(eventFrag->GetDetectorType());
1035  failedWord = x;
1036  } else {
1037  multipleErrors = true;
1038  }
1039  Push(*fBadOutputQueue, std::make_shared<TBadFragment>(*eventFrag, data, size, failedWord, multipleErrors));
1040  throw TGRSIDataParserException(fState, failedWord, multipleErrors);
1041  } // switch(eventFrag->GetModuleType())
1042  break;
1043  } // switch(packet)
1044  } // for(;x<size;x++)
1045 
1046  TParsingDiagnostics::Get()->BadFragment(eventFrag->GetDetectorType());
1049  failedWord = x;
1050  } else {
1051  multipleErrors = true;
1052  }
1053  Push(*fBadOutputQueue, std::make_shared<TBadFragment>(*eventFrag, data, size, failedWord, multipleErrors));
1054  throw TGRSIDataParserException(fState, failedWord, multipleErrors);
1055  return -x;
1056 }
1057 
1058 bool TGRSIDataParser::SetGRIFHeader(uint32_t value, const std::shared_ptr<TFragment>& frag, EBank bank)
1059 {
1060  if((value & 0xf0000000) != 0x80000000) {
1061  return false;
1062  }
1063  switch(bank) {
1064  case EBank::kGRF1: // header format from before May 2015 experiments
1065  // Sets:
1066  // The number of filters
1067  // The Data Type
1068  // Number of Pileups
1069  // Channel Address
1070  // Detector Type
1071  // frag->SetNumberOfFilters((value &0x0f000000)>> 24);
1072  frag->SetModuleType((value & 0x00e00000) >> 21);
1073  frag->SetNumberOfPileups((value & 0x001c0000) >> 18);
1074  frag->SetAddress((value & 0x0003fff0) >> 4);
1075  frag->SetDetectorType((value & 0x0000000f));
1076 
1077  // if(frag-DetectorType==2)
1078  // frag->ChannelAddress += 0x8000;
1079  break;
1080  case EBank::kGRF2:
1081  // Sets:
1082  // The number of filters
1083  // The Data Type
1084  // Number of Pileups
1085  // Channel Address
1086  // Detector Type
1087  frag->SetNumberOfPileups((value & 0x0c000000) >> 26);
1088  frag->SetModuleType((value & 0x03800000) >> 23);
1089  // frag->SetNumberOfFilters((value &0x00700000)>> 20);
1090  frag->SetAddress((value & 0x000ffff0) >> 4);
1091  frag->SetDetectorType((value & 0x0000000f));
1092 
1093  break;
1094  case EBank::kGRF3:
1095  case EBank::kGRF4:
1096  frag->SetModuleType((value & 0x0e000000) >> 25);
1097  frag->SetNumberOfWords((value & 0x01f00000) >> 20);
1098  frag->SetAddress((value & 0x000ffff0) >> 4);
1099  frag->SetDetectorType((value & 0x0000000f));
1100 
1101  break;
1102  default:
1103  std::cout<<"This bank is not yet defined."<<std::endl;
1104  return false;
1105  }
1106 
1107  return true;
1108 }
1109 
1110 bool TGRSIDataParser::SetGRIFPrimaryFilterPattern(uint32_t value, const std::shared_ptr<TFragment>& frag, EBank bank)
1111 {
1112  /// Sets the Griffin Primary Filter Pattern
1113  if((value & 0xc0000000) != 0x00000000) {
1114  return false;
1115  }
1116  switch(bank) {
1117  case EBank::kGRF1:
1118  case EBank::kGRF2:
1119  frag->SetTriggerBitPattern(value >> 16);
1120  // frag->SetPPGWord(value & 0x0000ffff);//This is due to new GRIFFIN data format
1121  break;
1122  case EBank::kGRF3:
1123  case EBank::kGRF4:
1124  frag->SetTriggerBitPattern(value >> 16);
1125  frag->SetNumberOfPileups(value & 0x1f);
1126  fFragmentHasWaveform = ((value & 0x8000) == 0x8000);
1127  break;
1128  default: return false;
1129  }
1130  return true;
1131 }
1132 
1133 bool TGRSIDataParser::SetGRIFPrimaryFilterId(uint32_t value, const std::shared_ptr<TFragment>& frag)
1134 {
1135  /// Sets the Griffin Primary filter ID and PPG
1136  if((value & 0x80000000) != 0x00000000) {
1137  return false;
1138  }
1139 
1140  frag->SetTriggerId(value & 0x7FFFFFFF); // REAL
1141  return true;
1142 }
1143 
1144 bool TGRSIDataParser::SetGRIFChannelTriggerId(uint32_t value, const std::shared_ptr<TFragment>& frag)
1145 {
1146  /// Sets the Griffin Channel Trigger ID
1147  if((value & 0xf0000000) != 0x90000000) {
1148  return false;
1149  }
1150  frag->SetChannelId(value & 0x0fffffff);
1151  return true;
1152 }
1153 
1154 bool TGRSIDataParser::SetGRIFNetworkPacket(uint32_t value, const std::shared_ptr<TFragment>& frag)
1155 {
1156  /// Ignores the network packet number (for now)
1157  if((value & 0xf0000000) != 0xd0000000) {
1158  return false;
1159  }
1160  if((value & 0x0f000000) == 0x0f000000 && frag->GetNetworkPacketNumber() > 0) {
1161  if(frag->GetZc() != 0) {
1162  return false;
1163  }
1164  // descant zero crossing time.
1165  frag->SetZc(value & 0x00ffffff);
1166  } else {
1167  frag->SetNetworkPacketNumber(value & 0x0fffffff);
1168  }
1169  return true;
1170 }
1171 
1172 bool TGRSIDataParser::SetGRIFTimeStampLow(uint32_t value, const std::shared_ptr<TFragment>& frag)
1173 {
1174  /// Sets the lower 28 bits of the griffin time stamp
1175  if((value & 0xf0000000) != 0xa0000000) {
1176  return false;
1177  }
1178  // we always get the lower 28 bits first
1179  frag->SetTimeStamp(value & 0x0fffffff);
1180  return true;
1181 }
1182 
1183 bool TGRSIDataParser::SetGRIFWaveForm(uint32_t value, const std::shared_ptr<TFragment>& frag)
1184 {
1185  /// Sets the Griffin waveform if record_waveform is set to true
1186  if(frag->GetWaveform()->size() > 100000) {
1187  std::cout<<"number of wave samples found is too great"<<std::endl;
1188  return false;
1189  }
1190 
1191  // to go from a 14-bit signed number to a 16-bit signed number, we simply set the two highest bits if the sign bit is set
1192  frag->AddWaveformSample((value & 0x2000) != 0u ? static_cast<Short_t>((value & 0x3fff) | 0xc000)
1193  : static_cast<Short_t>(value & 0x3fff));
1194  value = value >> 14;
1195  frag->AddWaveformSample((value & 0x2000) != 0u ? static_cast<Short_t>((value & 0x3fff) | 0xc000)
1196  : static_cast<Short_t>(value & 0x3fff));
1197 
1198  return true;
1199 }
1200 
1201 bool TGRSIDataParser::SetGRIFDeadTime(uint32_t value, const std::shared_ptr<TFragment>& frag)
1202 {
1203  /// Sets the Griffin deadtime and the upper 14 bits of the timestamp
1204  if((value & 0xf0000000) != 0xb0000000) {
1205  return false;
1206  }
1207  frag->SetDeadTime((value & 0x0fffc000) >> 14);
1208  // AppendTimeStamp simply adds the new value (not bitwise operation), so we just add the high bits
1209  frag->AppendTimeStamp(static_cast<Long64_t>(value & 0x00003fff)<<28);
1210  return true;
1211 }
1212 
1213 bool TGRSIDataParser::SetGRIFCc(uint32_t value, const std::shared_ptr<TFragment>& frag)
1214 {
1215  /// set the short integration and the lower 9 bits of the long integration
1216  if(frag->GetCcShort() != 0 || frag->GetCcLong() != 0) {
1217  return false;
1218  }
1219  frag->SetCcShort(value & 0x7ffff);
1220  frag->SetCcLong(value >> 19);
1221  return true;
1222 }
1223 
1224 bool TGRSIDataParser::SetGRIFPsd(uint32_t value, const std::shared_ptr<TFragment>& frag)
1225 {
1226  /// set the zero crossing and the higher 10 bits of the long integration
1227  if(frag->GetZc() != 0) { // low bits of ccLong have already been set
1228  return false;
1229  }
1230  frag->SetZc(value & 0x003fffff);
1231  frag->SetCcLong(frag->GetCcLong() | ((value & 0x7fe00000) >> 12)); // 21 bits from zero crossing minus 9 lower bits
1232  return true;
1233 }
1234 
1235 int TGRSIDataParser::RFScalerToFragment(uint32_t* data, const int size, const std::shared_ptr<TFragment>& frag)
1236 {
1237  // Parses special RF scaler events which contain only timestamps and fit paramteters
1238 
1239  ULong64_t ts = 0;
1240  ULong64_t tshigh;
1241  double rfFreq = -1.0;
1242  double rfPar[4];
1243  bool freqSet=false;
1244  bool tsSet=false;
1245  int failedWord = -1;
1246 
1247  int x=0;
1248  for(int i = 0; i < size; i++) {
1249 
1250  if(x >= size){
1251  //std::cout << "RF fragment missing frequency and/or timestamp info!" << std::endl;
1252  return -1;
1253  }
1254 
1255  uint32_t dword = data[x];
1256  uint32_t packet = dword >> 28;
1257  uint32_t value = dword & 0x0fffffff;
1258 
1259  switch(packet) {
1260  case 0x9:
1261  //RF frequency word
1262  rfFreq = static_cast<double>(value); //RF frequency (27-bit number) in cycles per 2^27 clock ticks or 1.34s
1263  freqSet=true;
1264  break;
1265  case 0xa:
1266  //timestamp words (low 0xa followed by high 0xb)
1267  ts = 0;
1268  ts |= value;
1269  x++;
1270  if((data[x] >> 28) == 0xb) {
1271  tshigh = data[x]; //need to convert the high timestamp data to a long int prior to shifting
1272  ts |= ((tshigh & 0x00003fff)<<28); //timestamp, in samples
1273  tsSet=true;
1274  }else{
1275  TParsingDiagnostics::Get()->BadFragment(frag->GetDetectorType());
1277  failedWord = x;
1278  Push(*fBadOutputQueue, std::make_shared<TBadFragment>(*frag, data, size, failedWord, false));
1279  //std::cout << "Invalid RF high time stamp!" << std::endl;
1280  return -1;
1281  }
1282  break;
1283  case 0xe:
1284  //std::cout << "Early end to RF fragment." << std::endl;
1285  TParsingDiagnostics::Get()->BadFragment(frag->GetDetectorType());
1287  failedWord = x;
1288  Push(*fBadOutputQueue, std::make_shared<TBadFragment>(*frag, data, size, failedWord, false));
1289  return -1;
1290  break;
1291  default:
1292  break;
1293  }
1294  x++;
1295  if(freqSet&&tsSet)
1296  break;
1297  }
1298 
1299  if(rfFreq < 0.0){
1300  //std::cout << "Bad RF frequency." << std::endl;
1301  TParsingDiagnostics::Get()->BadFragment(frag->GetDetectorType());
1303  failedWord = x;
1304  Push(*fBadOutputQueue, std::make_shared<TBadFragment>(*frag, data, size, failedWord, false));
1305  return -1;
1306  }
1307 
1308  frag->SetTimeStamp(ts);
1309 
1310  if(!(x<size-3)){
1311  //std::cout << "RF fragment does not contain all parameters." << std::endl;
1312  TParsingDiagnostics::Get()->BadFragment(frag->GetDetectorType());
1314  failedWord = x;
1315  Push(*fBadOutputQueue, std::make_shared<TBadFragment>(*frag, data, size, failedWord, false));
1316  return -1;
1317  }
1318  if((data[x]==data[x+1])&&(data[x]==data[x+2])&&(data[x]==data[x+3])){
1319  //std::cout << "Failed RF fit: all parameters are the same value." << std::endl;
1320  TParsingDiagnostics::Get()->BadFragment(frag->GetDetectorType());
1322  failedWord = x;
1323  Push(*fBadOutputQueue, std::make_shared<TBadFragment>(*frag, data, size, failedWord, false));
1324  return -1;
1325  }
1326 
1327  int pos=0;
1328  for(int i = 0; i < 4; i++) {
1329 
1330  uint32_t dword = data[x];
1331  uint32_t packet = dword >> 28;
1332 
1333  if(x<size){
1334  if((packet) == 0xe){
1335  //std::cout << "RF fragment unexpectedly ended early!" << std::endl;
1336  TParsingDiagnostics::Get()->BadFragment(frag->GetDetectorType());
1338  failedWord = x;
1339  Push(*fBadOutputQueue, std::make_shared<TBadFragment>(*frag, data, size, failedWord, false));
1340  return -1;
1341  }
1342  if((i!=2)&&(dword == 0)){
1343  //std::cout << "Failed RF fit: non-offset parameter is zero." << std::endl;
1344  TParsingDiagnostics::Get()->BadFragment(frag->GetDetectorType());
1346  failedWord = x;
1347  Push(*fBadOutputQueue, std::make_shared<TBadFragment>(*frag, data, size, failedWord, false));
1348  return -1;
1349  }
1350 
1351  if(dword & (1<<29)){
1352  //parameter value is negative
1353  //take two's complement
1354  for(int j=0;j<30;j++){
1355  if(dword & (1<<j)){
1356  pos=j;
1357  break;
1358  }
1359  }
1360  for(int j=pos+1;j<30;j++){
1361  dword ^= 1 << j;
1362  }
1363  rfPar[i] = static_cast<double>(-1.0*(dword & 0x03ffffff)); //RF fit parameters (30-bit numbers)
1364  }else{
1365  rfPar[i] = static_cast<double>(dword & 0x03ffffff); //RF fit parameters (30-bit numbers)
1366  }
1367 
1368  x++;
1369  }
1370  }
1371 
1372  //RF frequency and all 4 fit parameters were parsed without issue
1373  //convert these into the RF period and phase
1374 
1375  rfPar[0] = rfPar[0] / rfPar[3];
1376  rfPar[1] = rfPar[1] / rfPar[3];
1377  rfPar[2] = rfPar[2] / rfPar[3];
1378  double T = 1.34217728E9 / rfFreq; // period in ns
1379  double A = sqrt(rfPar[1] * rfPar[1] + rfPar[0] * rfPar[0]);
1380  double s = -rfPar[0] / A;
1381  double c = rfPar[1] / A;
1382  double rfPhaseShift; //the phase shift, in ns
1383  if(s >= 0) {
1384  rfPhaseShift = acos(c) * T / (2 * TMath::Pi());
1385  } else {
1386  rfPhaseShift = (1 - acos(c) / (2 * TMath::Pi())) * T;
1387  }
1388 
1389  //put the important info (phase shift, period) into the fragment
1390 
1391  frag->SetCharge(static_cast<float>(T)); //period stored as charge (where else would I put it?)
1392  frag->SetCfd(static_cast<float>(rfPhaseShift) * 1.6f); //phase shift in cfd units (this one seems reasonable)
1393 
1394  Push(fGoodOutputQueues, std::make_shared<TFragment>(*frag));
1395  return 1;
1396 }
1397 
1398 int TGRSIDataParser::GriffinDataToPPGEvent(uint32_t* data, int size, unsigned int, time_t)
1399 {
1400  auto* ppgEvent = new TPPGData;
1401  int x = 1; // We have already read the header so we can skip the 0th word.
1402 
1403  // The Network packet number is for debugging and is not always written to
1404  // the midas file.
1405  if(SetPPGNetworkPacket(data[x], ppgEvent)) { // The network packet placement is not yet stable.
1406  ++x;
1407  }
1408  if(SetNewPPGPattern(data[x], ppgEvent)) {
1409  ++x;
1410  }
1411 
1412  for(; x < size; x++) {
1413  uint32_t dword = data[x];
1414  uint32_t packet = dword & 0xf0000000;
1415  uint32_t value = dword & 0x0fffffff;
1416 
1417  switch(packet) {
1418  case 0x80000000: // The 8 packet type is for event headers
1419  // if this happens, we have "accidentally" found another event.
1420  return -x;
1421  case 0x90000000: // The b packet type contains the dead-time word
1422  SetOldPPGPattern(value, ppgEvent);
1423  break;
1424  case 0xd0000000:
1425  SetPPGNetworkPacket(dword, ppgEvent); // The network packet placement is not yet stable.
1426  break;
1427  case 0xa0000000: SetPPGLowTimeStamp(value, ppgEvent); break;
1428  case 0xb0000000: SetPPGHighTimeStamp(value, ppgEvent); break;
1429  case 0xe0000000:
1430  // if((value & 0xFFFF) == (ppgEvent->GetNewPPG())){
1431  TPPG::Get()->AddData(ppgEvent);
1432  TParsingDiagnostics::Get()->GoodFragment(-2); // use detector type -2 for PPG
1433  return x;
1434  //} else {
1435  // TParsingDiagnostics::Get()->BadFragment(-2); //use detector type -2 for PPG
1436  // return -x;
1437  //}
1438  break;
1439  };
1440  }
1441  delete ppgEvent;
1442  // No trailer found
1443  TParsingDiagnostics::Get()->BadFragment(-2); // use detector type -2 for PPG
1444  return -x;
1445 }
1446 
1447 bool TGRSIDataParser::SetNewPPGPattern(uint32_t value, TPPGData* ppgevent)
1448 {
1449  if((value & 0xf0000000) != 0x00000000) {
1450  return false;
1451  }
1452  ppgevent->SetNewPPG(value & 0x0fffffff);
1453  return true;
1454 }
1455 
1456 bool TGRSIDataParser::SetOldPPGPattern(uint32_t value, TPPGData* ppgevent)
1457 {
1458  ppgevent->SetOldPPG(value & 0x0fffffff);
1459  return true;
1460 }
1461 
1462 bool TGRSIDataParser::SetPPGNetworkPacket(uint32_t value, TPPGData* ppgevent)
1463 {
1464  // Ignores the network packet number (for now)
1465  if((value & 0xf0000000) != 0xd0000000) {
1466  return false;
1467  }
1468  ppgevent->SetNetworkPacketId(value & 0x00ffffff);
1469 
1470  return true;
1471 }
1472 
1473 bool TGRSIDataParser::SetPPGLowTimeStamp(uint32_t value, TPPGData* ppgevent)
1474 {
1475  // the PPG stores the raw values of low and high timestamp
1476  // SetTimeStamp caluculates the correct (multiplied by 10) timestamp from these
1477  // and is called by both SetLowTimeStamp and SetHighTimeStamp
1478  ppgevent->SetLowTimeStamp(value & 0x0fffffff);
1479  return true;
1480 }
1481 
1482 bool TGRSIDataParser::SetPPGHighTimeStamp(uint32_t value, TPPGData* ppgevent)
1483 {
1484  // the PPG stores the raw values of low and high timestamp
1485  // SetTimeStamp caluculates the correct (multiplied by 10) timestamp from these
1486  // and is called by both SetLowTimeStamp and SetHighTimeStamp
1487  ppgevent->SetHighTimeStamp(value & 0x0fffffff);
1488  return true;
1489 }
1490 
1491 int TGRSIDataParser::GriffinDataToScalerEvent(uint32_t* data, int address)
1492 {
1493  auto* scalerEvent = new TScalerData;
1494  scalerEvent->SetAddress(address);
1495  int x = 1; // We have already read the header so we can skip the 0th word.
1496  int failedWord = -1;
1497 
1498  // we expect a word starting with 0xd containing the network packet id
1499  // this is a different format than the others because it will not always be in the scaler word
1500  if(SetScalerNetworkPacket(data[x], scalerEvent)) {
1501  x++;
1502  }
1503 
1504  // we expect a word starting with 0xa containing the 28 lowest bits of the timestamp
1505  if(!SetScalerLowTimeStamp(data[x++], scalerEvent)) {
1506  TParsingDiagnostics::Get()->BadFragment(-3); // use detector type -3 for scaler data
1508  failedWord = x;
1509  throw TGRSIDataParserException(fState, failedWord, false);
1510  }
1511  // followed by four scaler words (32 bits each)
1512  for(int i = 0; i < 4; ++i) {
1513  if(!SetScalerValue(i, data[x++], scalerEvent)) {
1514  TParsingDiagnostics::Get()->BadFragment(-3); // use detector type -3 for scaler data
1516  failedWord = x;
1517  throw TGRSIDataParserException(fState, failedWord, false);
1518  }
1519  }
1520  // and finally the trailer word with the highest 24 bits of the timestamp
1521  int scalerType = 0;
1522  if(!SetScalerHighTimeStamp(data[x++], scalerEvent, scalerType)) {
1523  TParsingDiagnostics::Get()->BadFragment(-3); // use detector type -3 for scaler data
1525  failedWord = x;
1526  throw TGRSIDataParserException(fState, failedWord, false);
1527  }
1528 
1529  if(scalerType == 0) { // deadtime scaler
1530  TDeadtimeScalerQueue::Get()->Add(scalerEvent);
1531  } else if(scalerType == 1) { // rate scaler
1532  // the rate scaler has only one real value, the rate
1533  scalerEvent->ResizeScaler();
1534  TRateScalerQueue::Get()->Add(scalerEvent);
1535  } else { // unknown scaler type
1536  TParsingDiagnostics::Get()->BadFragment(-3); // use detector type -3 for scaler data
1538  failedWord = x;
1539  throw TGRSIDataParserException(fState, failedWord, false);
1540  }
1541 
1542  TParsingDiagnostics::Get()->GoodFragment(-3); // use detector type -3 for scaler data
1543  return x;
1544 }
1545 
1546 bool TGRSIDataParser::SetScalerNetworkPacket(uint32_t value, TScalerData* scalerEvent)
1547 {
1548  if((value >> 28) != 0xd) {
1549  return false;
1550  }
1551  scalerEvent->SetNetworkPacketId(value & 0x0fffffff);
1552  return true;
1553 }
1554 
1555 bool TGRSIDataParser::SetScalerLowTimeStamp(uint32_t value, TScalerData* scalerEvent)
1556 {
1557  // the scaler stores the raw values of low and high timestamp
1558  // GetTimeStamp caluculates the correct (multiplied by 10) timestamp from these
1559  if((value >> 28) != 0xa) {
1560  return false;
1561  }
1562  scalerEvent->SetLowTimeStamp(value & 0x0fffffff);
1563  return true;
1564 }
1565 
1566 bool TGRSIDataParser::SetScalerHighTimeStamp(uint32_t value, TScalerData* scalerEvent, int& type)
1567 {
1568  // the scaler stores the raw values of low and high timestamp
1569  // GetTimeStamp caluculates the correct (multiplied by 10) timestamp from these
1570  if((value >> 28) != 0xe || (value & 0xff) != (scalerEvent->GetLowTimeStamp() >> 20)) {
1571  return false;
1572  }
1573  scalerEvent->SetHighTimeStamp((value >> 8) & 0x0000ffff);
1574  type = (value >> 24 & 0xf);
1575  return true;
1576 }
1577 
1578 bool TGRSIDataParser::SetScalerValue(int index, uint32_t value, TScalerData* scalerEvent)
1579 {
1580  scalerEvent->SetScaler(index, value);
1581  return true;
1582 }
1583 
1584 int TGRSIDataParser::CaenPsdToFragment(uint32_t* data, int size, std::shared_ptr<TMidasEvent>& event)
1585 {
1586  /// Converts a Caen flavoured MIDAS events into TFragments and returns the number of events processed
1587  std::shared_ptr<TFragment> eventFrag = std::make_shared<TFragment>();
1588  int w = 0;
1589  int nofFragments = 0;
1590 
1591  if(fOptions == nullptr) {
1593  }
1594 
1595  for(int board = 0; w < size; ++board) {
1596  // read board aggregate header
1597  if(data[w]>>28 != 0xa) {
1598  if(data[w] == 0x0) {
1599  while(w < size) {
1600  if(data[w++] != 0x0) {
1601  if(!fOptions->SuppressErrors()) {
1602  std::cerr<<board<<". board - failed on first word, found empty word, but not all following words were empty: "<<w-1<<" 0x"<<std::hex<<std::setw(8)<<std::setfill('0')<<data[w-1]<<std::dec<<std::setfill(' ')<<std::endl;
1603  }
1604  return -w;
1605  }
1606  }
1607  return nofFragments;
1608  }
1609  if(!fOptions->SuppressErrors()) {
1610  std::cerr<<board<<". board - failed on first word 0x"<<std::hex<<std::setw(8)<<std::setfill('0')<<data[w]<<std::dec<<std::setfill(' ')<<", highest nibble should have been 0xa!"<<std::endl;
1611  }
1612  return -w;
1613  }
1614  int32_t numWordsBoard = data[w++]&0xfffffff; // this is the number of 32-bit words from this board
1615  if(w - 1 + numWordsBoard > size) {
1616  if(!fOptions->SuppressErrors()) {
1617  std::cerr<<"0 - Missing words, at word "<<w-1<<", expecting "<<numWordsBoard<<" more words for board "<<board<<" (bank size "<<size<<")"<<std::endl;
1618  }
1619  return -w;
1620  }
1621  uint8_t boardId = data[w]>>27; // GEO address of board (can be set via register 0xef08 for VME)
1622  //uint16_t pattern = (data[w]>>8) & 0x7fff; // value read from LVDS I/O (VME only)
1623  uint8_t channelMask = data[w++]&0xff; // which channels are in this board aggregate
1624  ++w;//uint32_t boardCounter = data[w++]&0x7fffff; // ??? "counts the board aggregate"
1625  uint32_t boardTime = data[w++]; // time of creation of aggregate (does not correspond to a physical quantity)
1626  //if(boardCounter < gBoardCounter) {
1627  // std::cerr<<"current board counter "<<boardCounter<<" is less than previous one "<<gBoardCounter<<", skipping this data"<<std::endl;
1628  // return nofFragments;
1629  //}
1630  //gBoardCounter = boardCounter;
1631 
1632  for(uint8_t channel = 0; channel < 16; channel += 2) {
1633  if(((channelMask>>(channel/2)) & 0x1) == 0x0) {
1634  continue;
1635  }
1636  // read channel aggregate header
1637  if(data[w]>>31 != 0x1) {
1638  if(!fOptions->SuppressErrors()) {
1639  std::cerr<<"Failed on first word 0x"<<std::hex<<std::setw(8)<<std::setfill('0')<<data[w]<<std::dec<<std::setfill(' ')<<", highest bit should have been set!"<<std::endl;
1640  }
1641  return -w;
1642  }
1643  int32_t numWords = data[w++]&0x3fffff;//per channel
1644  if(w >= size) {
1645  if(!fOptions->SuppressErrors()) {
1646  std::cerr<<"1 - Missing words, got only "<<w-1<<" words for channel "<<channel<<" (bank size "<<size<<")"<<std::endl;
1647  }
1648  return -w;
1649  }
1650  if(((data[w]>>29) & 0x3) != 0x3) {
1651  if(!fOptions->SuppressErrors()) {
1652  std::cerr<<"Failed on second word 0x"<<std::hex<<std::setw(8)<<std::setfill('0')<<data[w]<<std::dec<<std::setfill(' ')<<", bits 29 and 30 should have been set!"<<std::endl;
1653  }
1654  return -w;
1655  }
1656  bool dualTrace = ((data[w]>>31) == 0x1);
1657  bool extras = (((data[w]>>28) & 0x1) == 0x1);
1658  bool waveform = (((data[w]>>27) & 0x1) == 0x1);
1659  uint8_t extraFormat = ((data[w]>>24) & 0x7);
1660  //for now we ignore the information which traces are stored:
1661  //bits 22,23: if(dualTrace) 00 = "Input and baseline", 01 = "CFD and Baseline", 10 = "Input and CFD"
1662  // else 00 = "Input", 01 = "CFD"
1663  //bits 19,20,21: 000 = "Long gate", 001 = "over thres.", 010 = "shaped TRG", 011 = "TRG Val. Accept. Win.", 100 = "Pile Up", 101 = "Coincidence", 110 = reserved, 111 = "Trigger"
1664  //bits 16,17,18: 000 = "Short gate", 001 = "over thres.", 010 = "TRG valid.", 011 = "TRG HoldOff", 100 = "Pile Up", 101 = "Coincidence", 110 = reserved, 111 = "Trigger"
1665  int numSampleWords = 4*(data[w++]&0xffff);// this is actually the number of samples divided by eight, 2 sample per word => 4*
1666  if(w >= size) {
1667  if(!fOptions->SuppressErrors()) {
1668  std::cerr<<"2 - Missing words, got only "<<w-1<<" words for channel "<<channel<<" (bank size "<<size<<")"<<std::endl;
1669  }
1670  return -w;
1671  }
1672  int eventSize = numSampleWords+2; // +2 = trigger time words and charge word
1673  if(extras) ++eventSize;
1674  if(numWords%eventSize != 2 && !(eventSize == 2 && numWords%eventSize == 0)) { // 2 header words plus n*eventSize should make up one channel aggregate
1675  if(!fOptions->SuppressErrors()) {
1676  std::cerr<<numWords<<" words in channel aggregate, event size is "<<eventSize<<" => "<<static_cast<double>(numWords-2.)/static_cast<double>(eventSize)<<" events?"<<std::endl;
1677  }
1678  return -w;
1679  }
1680 
1681  // read channel data
1682  for(int ev = 0; ev < (numWords-2)/eventSize; ++ev) { // -2 = 2 header words for channel aggregate
1683  eventFrag->SetDaqTimeStamp(boardTime);
1684  eventFrag->SetAddress(0x8000 + (boardId * 0x100) + channel + (data[w]>>31)); // highest bit indicates odd channel
1685  if(eventFrag->GetAddress() == 0x8000) eventFrag->SetDetectorType(9); //ZDS will always be in channel 0
1686  else eventFrag->SetDetectorType(6);
1687  // these timestamps are in 2ns units
1688  eventFrag->SetTimeStamp(data[w] & 0x7fffffff);
1689  ++w;
1690  if(waveform) {
1691  if(w + numSampleWords >= size) { // need to read at least the sample words plus the charge/extra word
1692  if(!fOptions->SuppressErrors()) {
1693  std::cerr<<"3 - Missing "<<numSampleWords<<" waveform words, got only "<<w-1<<" words for channel "<<channel<<" (bank size "<<size<<")"<<std::endl;
1694  }
1695  return -w;
1696  }
1697  for(int s = 0; s < numSampleWords && w < size; ++s, ++w) {
1698  //eventFrag->AddDigitalWaveformSample(0, (data[w]>>14)&0x1);
1699  //eventFrag->AddDigitalWaveformSample(1, (data[w]>>15)&0x1);
1700  if(dualTrace) {
1701  // all even samples are from the first trace, all odd ones from the second trace
1702  //eventFrag->AddWaveformSample(data[w]&0x3fff);
1703  //eventFrag->AddWaveformSample((data[w]>>16)&0x3fff);
1704  eventFrag->AddWaveformSample(data[w]&0xffff);
1705  eventFrag->AddWaveformSample((data[w]>>16)&0xffff);
1706  } else {
1707  // both samples are from the first trace
1708  //eventFrag->AddWaveformSample(data[w]&0x3fff);
1709  //eventFrag->AddWaveformSample((data[w]>>16)&0x3fff);
1710  eventFrag->AddWaveformSample(data[w]&0xffff);
1711  eventFrag->AddWaveformSample((data[w]>>16)&0xffff);
1712  }
1713  //eventFrag->AddDigitalWaveformSample(0, (data[w]>>30)&0x1);
1714  //eventFrag->AddDigitalWaveformSample(1, (data[w]>>31)&0x1);
1715  }
1716  } else {
1717  if(w >= size) { // need to read at least the sample words plus the charge/extra word
1718  if(!fOptions->SuppressErrors()) {
1719  std::cerr<<"3 - Missing words, got only "<<w-1<<" words for channel "<<channel<<" (bank size "<<size<<")"<<std::endl;
1720  }
1721  return -w;
1722  }
1723  }
1724  if(extras) {
1725  //std::cout<<eventFrag->GetAddress()<<" - extra word format "<<static_cast<int>(extraFormat)<<": 0x"<<std::hex<<data[w]<<std::dec<<std::endl;
1726  switch(extraFormat) {
1727  case 0: // [31:16] extended time stamp, [15:0] baseline*4
1728  //eventFrag->Baseline(data[w]&0xffff);
1729  eventFrag->SetTimeStamp(eventFrag->GetTimeStamp() | static_cast<uint64_t>(data[w]&0xffff0000)<<15);
1730  break;
1731  case 1: // [31:16] extended time stamp, 15 trigger lost, 14 over range, 13 1024 triggers, 12 n lost triggers
1732  eventFrag->SetNetworkPacketNumber((data[w]>>12)&0xf);
1733  //eventFrag->NLostCount(((data[w]>>12)&0x1) == 0x1);
1734  //eventFrag->KiloCount(((data[w]>>13)&0x1) == 0x1);
1735  //eventFrag->OverRange(((data[w]>>14)&0x1) == 0x1);
1736  //eventFrag->LostTrigger(((data[w]>>15)&0x1) == 0x1);
1737  eventFrag->SetTimeStamp(eventFrag->GetTimeStamp() | static_cast<uint64_t>(data[w]&0xffff0000)<<15);
1738  break;
1739  case 2: // [31:16] extended time stamp, 15 trigger lost, 14 over range, 13 1024 triggers, 12 n lost triggers, [9:0] fine time stamp
1740  eventFrag->SetTimeStamp(eventFrag->GetTimeStamp() | static_cast<uint64_t>(data[w]&0xffff0000)<<15);
1741  eventFrag->SetCfd(data[w]&0x3ff);
1742  eventFrag->SetNetworkPacketNumber((data[w]>>12)&0xf);
1743  //eventFrag->NLostCount(((data[w]>>12)&0x1) == 0x1);
1744  //eventFrag->KiloCount(((data[w]>>13)&0x1) == 0x1);
1745  //eventFrag->OverRange(((data[w]>>14)&0x1) == 0x1);
1746  //eventFrag->LostTrigger(((data[w]>>15)&0x1) == 0x1);
1747  break;
1748  case 4: // [31:16] lost trigger counter, [15:0] total trigger counter
1749  eventFrag->SetAcceptedChannelId(data[w]&0xffff); // this is actually the lost trigger counter!
1750  eventFrag->SetChannelId(data[w]>>16);
1751  break;
1752  case 5: // [31:16] CFD sample after zero cross., [15:0] CFD sample before zero cross.
1753  //eventFrag->CfdAfterZC(data[w]&0xffff);
1754  //eventFrag->CfdBeforeZC(data[w]>>16);
1755  w++;
1756  break;
1757  case 7: // fixed value of 0x12345678
1758  if(data[w] != 0x12345678) {
1759  if(!fOptions->SuppressErrors()) {
1760  std::cerr<<"Failed to get debug data word 0x12345678, got "<<std::hex<<std::setw(8)<<std::setfill('0')<<data[w]<<std::dec<<std::setfill(' ')<<std::endl;
1761  }
1762  break;
1763  }
1764  break;
1765  default:
1766  break;
1767  }
1768  ++w;
1769  }
1770  eventFrag->SetCcShort(data[w]&0x7fff);
1771  eventFrag->SetCcLong((data[w]>>15) & 0x1);//this is actually the over-range bit!
1772  eventFrag->SetCharge(static_cast<Int_t>(data[w++]>>16));
1773  Push(fGoodOutputQueues, std::make_shared<TFragment>(*eventFrag));
1774  eventFrag->Clear();
1775  ++nofFragments;
1776  event->IncrementGoodFrags();
1777  } // while(w < size)
1778  } // for(uint8_t channel = 0; channel < 16; channel += 2)
1779  } // for(int board = 0; w < size; ++board)
1780 
1781  return nofFragments;
1782 }
1783 
1784 int TGRSIDataParser::CaenPhaToFragment(uint32_t* data, int size, std::shared_ptr<TMidasEvent>& event)
1785 {
1786  /// Converts a Caen flavoured MIDAS events into TFragments and returns the number of events processed
1787  std::shared_ptr<TFragment> eventFrag = std::make_shared<TFragment>();
1788  int w = 0;
1789  int nofFragments = 0;
1790 
1791  if(fOptions == nullptr) {
1793  }
1794 
1795  for(int board = 0; w < size; ++board) {
1796  // read board aggregate header
1797  if(data[w]>>28 != 0xa) {
1798  if(data[w] == 0x0) {
1799  while(w < size) {
1800  if(data[w++] != 0x0) {
1801  if(!fOptions->SuppressErrors()) {
1802  std::cerr<<board<<". board - failed on first word, found empty word, but not all following words were empty: "<<w-1<<" 0x"<<std::hex<<std::setw(8)<<std::setfill('0')<<data[w-1]<<std::dec<<std::setfill(' ')<<std::endl;
1803  }
1804  return -w;
1805  }
1806  }
1807  return nofFragments;
1808  }
1809  if(!fOptions->SuppressErrors()) {
1810  std::cerr<<board<<". board - failed on first word 0x"<<std::hex<<std::setw(8)<<std::setfill('0')<<data[w]<<std::dec<<std::setfill(' ')<<", highest nibble should have been 0xa!"<<std::endl;
1811  }
1812  return -w;
1813  }
1814  int32_t numWordsBoard = data[w++]&0xfffffff; // this is the number of 32-bit words from this board
1815  if(w - 1 + numWordsBoard > size) {
1816  if(!fOptions->SuppressErrors()) {
1817  std::cerr<<"0 - Missing words, at word "<<w-1<<", expecting "<<numWordsBoard<<" more words for board "<<board<<" (bank size "<<size<<")"<<std::endl;
1818  }
1819  return -w;
1820  }
1821  uint8_t boardId = data[w]>>27; // GEO address of board (can be set via register 0xef08 for VME)
1822  //bool failFlag = (data[w]>>26) & 0x1; // board fail flag (PLL lock lost or overheating)
1823  //uint16_t pattern = (data[w]>>8) & 0x7fff; // value read from LVDS I/O (VME only)
1824  uint8_t channelMask = data[w++]&0xff; // which channels are in this board aggregate
1825  ++w;//uint32_t boardCounter = data[w++]&0x7fffff; // ??? "counts the board aggregate"
1826  uint32_t boardTime = data[w++]; // time of creation of aggregate (does not correspond to a physical quantity)
1827  //if(boardCounter < gBoardCounter) {
1828  // std::cerr<<"current board counter "<<boardCounter<<" is less than previous one "<<gBoardCounter<<", skipping this data"<<std::endl;
1829  // return nofFragments;
1830  //}
1831  //gBoardCounter = boardCounter;
1832 
1833  for(uint8_t channel = 0; channel < 8; ++channel) {
1834  // check if the bit for this channel is set in the channel mask
1835  if(((channelMask>>channel) & 0x1) == 0x0) {
1836  continue;
1837  }
1838  // read channel aggregate header
1839  if(data[w]>>31 != 0x1) {
1840  if(!fOptions->SuppressErrors()) {
1841  std::cerr<<"Failed on first word 0x"<<std::hex<<std::setw(8)<<std::setfill('0')<<data[w]<<std::dec<<std::setfill(' ')<<", highest bit should have been set (to get format info)!"<<std::endl;
1842  }
1843  return -w;
1844  }
1845  int32_t numWords = data[w++]&0x7fffffff;//per channel
1846  if(w >= size) {
1847  if(!fOptions->SuppressErrors()) {
1848  std::cerr<<"1 - Missing words, got only "<<w-1<<" words for channel "<<channel<<" (bank size "<<size<<")"<<std::endl;
1849  }
1850  return -w;
1851  }
1852  //bool dualTrace = ((data[w]>>31) == 0x1);
1853  //bool energyEnabled = ((data[w]>>30) == 0x1);
1854  //bool timeEnabled = ((data[w]>>29) == 0x1);
1855  bool extras = (((data[w]>>28) & 0x1) == 0x1);
1856  bool waveform = (((data[w]>>27) & 0x1) == 0x1);
1857  uint8_t extraFormat = ((data[w]>>24) & 0x7);
1858  //for now we ignore the information which traces are stored:
1859  //bits 22,23: 00 = "Input", 01 = "RC-CR - first step", 10 = "RC-CR2 - second step", 11 = "Trapezoid"
1860  //bits 20,21: 00 = "Input", 01 = "Threshold - of RC-CR2", 10 = "Trapezoid minus baseline", 11 = "baseline of trapezoid"
1861  //bits 16-19: 0000 = "Peaking" - aka when energy is evaluated,
1862  // 0001 = "Armed" - when RC-CR2 crosses threshold,
1863  // 0010 = "Peak Run" - starts with trigger until end of event,
1864  // 0011 = "Pile-Up" - time interval when energy calc. is disabled due to pile-up,
1865  // 0100 = "Peaking" - aka when energy is evaluated (again?),
1866  // 0101 = "Trg Validation Window" - trigger validation acceptance window TVAW,
1867  // 0110 = "BSL Freeze" - shows when baseline is frozen for energy evaluation,
1868  // 0111 = "Trg Holdoff" - shows trigger holdoff parameter,
1869  // 1000 = "Trg Validation" - shows trigger validation signal TRG_VAL,
1870  // 1001 = "Acq Busy" - 1 if board is busy or vetoed,
1871  // 1010 = "Trg Window" - not used,
1872  // 1011 = "Ext Trg" - shows external trigger when available,
1873  // 1100 = "Busy" - shows when memory board is full
1874  int numSampleWords = 4*(data[w++]&0xffff);// this is actually the number of samples divided by eight, 2 sample per word => 4*
1875  if(w >= size) {
1876  if(!fOptions->SuppressErrors()) {
1877  std::cerr<<"2 - Missing words, got only "<<w-1<<" words for channel "<<channel<<" (bank size "<<size<<")"<<std::endl;
1878  }
1879  return -w;
1880  }
1881  int eventSize = numSampleWords+2; // +2 = trigger time words and charge word
1882  if(extras) ++eventSize;
1883  if(numWords%eventSize != 2 && !(eventSize == 2 && numWords%eventSize == 0)) { // 2 header words plus n*eventSize should make up one channel aggregate
1884  if(!fOptions->SuppressErrors()) {
1885  std::cerr<<numWords<<" words in channel aggregate, event size is "<<eventSize<<" ("<<numWords%eventSize<<") => "<<static_cast<double>(numWords-2.)/static_cast<double>(eventSize)<<" events?"<<std::endl;
1886  }
1887  return -w;
1888  }
1889 
1890  // read channel data
1891  for(int ev = 0; ev < (numWords-2)/eventSize; ++ev) { // -2 = 2 header words for channel aggregate
1892  eventFrag->SetDaqTimeStamp(boardTime);
1893  eventFrag->SetAddress(0x8000 + (boardId * 0x100) + channel + (data[w]>>31)); // highest bit indicates odd channel
1894  eventFrag->SetDetectorType(0); // PHA firmware only used for HPGe?
1895  // these timestamps are in 2ns units
1896  eventFrag->SetTimeStamp(data[w++] & 0x7fffffff);
1897  if(waveform) {
1898  if(w + numSampleWords >= size) { // need to read at least the sample words plus the charge/extra word
1899  if(!fOptions->SuppressErrors()) {
1900  std::cerr<<"3 - Missing "<<numSampleWords<<" waveform words, got only "<<w-1<<" words for channel "<<channel<<" (bank size "<<size<<")"<<std::endl;
1901  }
1902  return -w;
1903  }
1904  for(int s = 0; s < numSampleWords && w < size; ++s, ++w) {
1905  // we don't care if we use dual trace and which bits are what (analog of digital waveform)
1906  // everything gets put into the normale waveform and will have to be separated during analysis
1907  // higher bits are later sample
1908  eventFrag->AddWaveformSample(data[w]&0xffff);
1909  eventFrag->AddWaveformSample((data[w]>>16)&0xffff);
1910  }
1911  } else {
1912  if(w >= size) { // need to read at least the sample words plus the charge/extra word
1913  if(!fOptions->SuppressErrors()) {
1914  std::cerr<<"3 - Missing words, got only "<<w-1<<" words for channel "<<channel<<" (bank size "<<size<<")"<<std::endl;
1915  }
1916  return -w;
1917  }
1918  }
1919  if(extras) {
1920  //std::cout<<eventFrag->GetAddress()<<" - extra word format "<<static_cast<int>(extraFormat)<<": 0x"<<std::hex<<data[w]<<std::dec<<std::endl;
1921  switch(extraFormat) {
1922  case 0: // [31:16] extended time stamp, [15:0] trapezoid baseline*4
1923  //eventFrag->Baseline(data[w]&0xffff);
1924  eventFrag->SetTimeStamp(eventFrag->GetTimeStamp() | static_cast<uint64_t>(data[w]&0xffff0000)<<15);
1925  break;
1926  case 2: // [31:16] extended time stamp, [15:0] fine time stamp (linear int. of RC-CR2 before and after zero-crossing)
1927  eventFrag->SetTimeStamp(eventFrag->GetTimeStamp() | static_cast<uint64_t>(data[w]&0xffff0000)<<15);
1928  eventFrag->SetCfd(data[w]&0xffff);
1929  break;
1930  case 4: // [31:16] lost trigger counter, [15:0] total trigger counter
1931  eventFrag->SetAcceptedChannelId(data[w]&0xffff); // this is actually the lost trigger counter!
1932  eventFrag->SetChannelId(data[w]>>16);
1933  break;
1934  case 5: // [31:16] sample before zero cross., [15:0] sample after zero cross.
1935  //eventFrag->CfdBeforeZC(data[w]&0xffff);
1936  //eventFrag->CfdAfterZC(data[w]>>16);
1937  ++w;
1938  break;
1939  case 1: // reserved
1940  case 3: // reserved
1941  case 7: // reserved
1942  break;
1943  default:
1944  break;
1945  }
1946  ++w;
1947  }
1948  // highest bit is actually the pile-up or roll-over bit!
1949  eventFrag->SetCharge(static_cast<Int_t>(data[w]&0xffff));
1950  // extras [20:16] or [23:16]?
1951  // 0 - lost event due to full memory board
1952  // 1 - roll over of time stamp (set by bit[26] of 0x1n80 to create fake event with this bit set)
1953  // 2 - reserved
1954  // 3 - fake event - from time stamp roll-over
1955  // 4 - input saturation
1956  // 5 - lost trigger - every n lost events this flag is high (n from bits[17:16] of 0x1na0
1957  // 6 - total trigger - every n total events this flag is high (n from bits[17:16] of 0x1na0
1958  // 7 - match coincidence - if bit[19] of 0x1na0 set then all events matching coincidence criteria are saved with this bit
1959  // 8 - no match coincidence - if bit[19] of 0x1na0 set then all events NOT matching coincidence criteria are saved with this bit
1960  ++w;
1961  Push(fGoodOutputQueues, std::make_shared<TFragment>(*eventFrag));
1962  eventFrag->Clear();
1963  ++nofFragments;
1964  event->IncrementGoodFrags();
1965  } // while(w < size)
1966  } // for(uint8_t channel = 0; channel < 16; channel += 2)
1967  } // for(int board = 0; w < size; ++board)
1968 
1969  return nofFragments;
1970 }
1971 
1972 /////////////***************************************************************/////////////
1973 /////////////***************************************************************/////////////
1974 /////////////***************************************************************/////////////
1975 /////////////***************************************************************/////////////
1976 /////////////***************************************************************/////////////
1977 /////////////***************************************************************/////////////
1978 
1979 int TGRSIDataParser::EPIXToScalar(float* data, int size, unsigned int midasSerialNumber, time_t midasTime)
1980 {
1981  int NumFragsFound = 1;
1982  std::shared_ptr<TEpicsFrag> EXfrag = std::make_shared<TEpicsFrag>();
1983 
1984  EXfrag->fDaqTimeStamp = midasTime;
1985  EXfrag->fDaqId = midasSerialNumber;
1986 
1987  for(int x = 0; x < size; x++) {
1988  EXfrag->fData.push_back(data[x]);
1989  EXfrag->fName.push_back(TEpicsFrag::GetEpicsVariableName(x));
1990  }
1991 
1992  fScalerOutputQueue->Push(EXfrag);
1993  return NumFragsFound;
1994 }
1995 
1996 /////////////***************************************************************/////////////
1997 /////////////***************************************************************/////////////
1998 /////////////**************************EMMA Stuff***************************/////////////
1999 /////////////***************************************************************/////////////
2000 /////////////***************************************************************/////////////
2001 /////////////***************************************************************/////////////
2002 
2003 static Long64_t xferhfts; // Time stamp to be transferred from ADC to TDC; 10 ns ticks
2004 static time_t xfermidts; // Midas time stamp of events, hopefully the same
2005 unsigned int xfermidsn; // Midas serial number
2006 
2007 
2008 int TGRSIDataParser::EmmaMadcDataToFragment(uint32_t* data, int size, std::shared_ptr<TMidasEvent>& event)
2009 {
2010  /// Converts a MIDAS File from the Emma DAQ into a TFragment.
2011  int numFragsFound = 0;
2012  std::shared_ptr<TFragment> eventFrag = std::make_shared<TFragment>();
2013  xfermidts = event->GetTimeStamp();// to check against EMMT bank
2014  eventFrag->SetDaqTimeStamp(xfermidts);
2015  xfermidsn = event->GetSerialNumber(); // to chck againts EMMT bank
2016  eventFrag->SetDaqId(xfermidsn);
2017  eventFrag->SetDetectorType(12);
2018 
2019  int x = 0;
2020  uint32_t dword = *(data + x);
2021 
2022  uint32_t type;
2023  uint32_t adcchannel;
2024  uint32_t adcdata;
2025  uint32_t adctimestamp;
2026  uint32_t adchightimestamp;
2027 
2028  eventFrag->SetTimeStamp(0);
2029  for(x=size; x-- > 0; ) { // Reads the event backwards
2030  dword = *(data + x);
2031  type = (dword & 0xf0000000) >> 28;
2032  switch(type) {
2033  case 0x0: // Reads the charge and channel number
2034  {
2035  if((dword & 0x00800000) != 0) {
2036  adchightimestamp=dword&0x0000ffff;
2037  eventFrag->AppendTimeStamp((static_cast<Long64_t>(adchightimestamp))*static_cast<Long64_t>(0x0000000040000000)); // This should shift the time stamp 30 bits
2038  xferhfts = eventFrag->GetTimeStamp();
2039  } else if ((dword & 0x04000000) != 0) { // GH verify that this is a good ADC reading
2040  adcchannel = (dword>>16)&0x1F; // ADC Channel Number
2041  adcdata = (dword & 0xfff); // ADC Charge
2042  std::shared_ptr<TFragment> transferfrag = std::make_shared<TFragment>(*eventFrag);
2043  transferfrag->SetCharge(static_cast<Int_t>(adcdata));
2044  transferfrag->SetAddress(0x800000 + adcchannel);
2045  TChannel* chan = TChannel::GetChannel(transferfrag->GetAddress(), false);
2046  if(chan == nullptr) {
2047  chan = fChannel;
2048  }
2049  Push(fGoodOutputQueues, transferfrag);
2050  numFragsFound++;
2051  }
2052  }
2053  break;
2054 
2055  case 0x4: // First DWORD in event, read last and writes the fragment
2056  // numFragsFound++;
2057  eventFrag = nullptr;
2058  return numFragsFound;
2059  break;
2060 
2061  case 0xe:
2062  case 0xf:
2063  case 0xd:
2064  case 0xc: // Last 30 bits of timestamp
2065  adctimestamp =(dword&0x3FFFFFFF);
2066  eventFrag->AppendTimeStamp(static_cast<Long64_t>(adctimestamp));
2067  break;
2068  default: break;
2069  } // end swich
2070  } // end for read backwards
2071 
2072  return numFragsFound;
2073 }
2074 
2075 // kludge by GH
2076 static uint32_t wraparoundcounter = 0xffffffff; // Needed for bad data at start of run before GRIFFIN starts
2077 static uint32_t lasttimestamp; // "last" time stamp for simple wraparound algorightm
2078 static uint32_t countsbetweenwraps; // number of counts between wraparounds
2079 
2080 int TGRSIDataParser::EmmaTdcDataToFragment(uint32_t* data, int size, std::shared_ptr<TMidasEvent>& event)
2081 {
2082  /// Building TDC events, duplicating logic from EmmaMadcDataToFragment
2083  int numFragsFound = 0;
2084  std::shared_ptr<TFragment> eventFrag = std::make_shared<TFragment>();
2085  eventFrag->SetDaqTimeStamp(event->GetTimeStamp());
2086  eventFrag->SetDaqId(event->GetSerialNumber());
2087  eventFrag->SetDetectorType(13);
2088 
2089  int x = 0;
2090  int failedWord = -1; // Variable stores which word we failed on (if we fail). This is somewhat duplicate information
2091  // to fState, but makes things easier to track.
2092  bool multipleErrors = false; // Variable to store if multiple errors occured parsing one fragment
2093  uint32_t tmpTimestamp = 0;
2094  uint32_t tmpAddress = 0;
2095  Long64_t ts;
2096 
2097  std::vector<uint32_t> addresses;
2098  std::vector<uint32_t> charges;
2099 
2100  // we simply loop through the data and read what we get. No checks are made that every word we want is present.
2101  for(x=0; x < size; ++x) {
2102  switch((data[x] >> 27) & 0x1F) {
2103  case 0x8: //global header
2104  eventFrag->SetModuleType(data[x] & 0x1f); // GEO
2105  eventFrag->SetAcceptedChannelId((data[x] >> 5) & 0x3fffff); // event count
2106  break;
2107  case 0x1: //TDC header
2108  tmpAddress = (data[x] >> 16) & 0x300;//16 = 24 - 8
2109  eventFrag->SetChannelId((data[x] >> 12) & 0xfff); // event id
2110  eventFrag->SetNetworkPacketNumber(data[x] & 0xfff); // bunch id
2111  break;
2112  case 0x0: // TDC measurement
2113  // we can get multiple of these per event, but we need the subsequent information from the trailer etc.
2114  // so we store the words for now and build fragments at the very end
2115  //
2116  // we use the trailing/leading bit as additional address information
2117  // VB's original code: addresses.push_back(((data[x] >> 18) & 0x800) | tmpAddress | ((data[x] >> 19) & 0x7f));//15 = 26 - 11
2118  addresses.push_back(0x900000 + ((data[x] >> 19) & 0xff ) ); // address = 0x00900000 + channel + 0x80 for a trailing measurement
2119  charges.push_back(data[x] & 0x7ffff);
2120  break;
2121  case 0x3: // TDC trailer
2122  if((tmpAddress != ((data[x] >> 16) & 0x300)) || (eventFrag->GetChannelId() != ((data[x] >> 12) & 0xfff))) {
2123  // either the trailer tdc doesn't match the header tdc, or the trailer event id doesn't match the header event id
2124  TParsingDiagnostics::Get()->BadFragment(13); // hard-coded 13 for TDC for now
2127  failedWord = x;
2128  } else {
2129  multipleErrors = true;
2130  }
2131  Push(*fBadOutputQueue, std::make_shared<TBadFragment>(*eventFrag, data, size, failedWord, multipleErrors));
2132  }
2133  eventFrag->SetNumberOfPileups(data[x] & 0xfff);
2134  break;
2135  case 0x4: // TDC error
2136  eventFrag->SetAddress((data[x] >> 16) & 0x300);//16 = 24 - 8
2137  eventFrag->SetCharge(static_cast<Int_t>((data[x]) & 0xFFF)); // error flags
2138  TParsingDiagnostics::Get()->BadFragment(13); // hard-coded 13 for TDC for now
2141  failedWord = x;
2142  } else {
2143  multipleErrors = true;
2144  }
2145  Push(*fBadOutputQueue, std::make_shared<TBadFragment>(*eventFrag, data, size, failedWord, multipleErrors));
2146  break;
2147  case 0x11: // extended trigger time
2148  tmpTimestamp = (data[x] & 0x7FFFFFF) << 5;
2149  break;
2150  case 0x10: // trailer
2151  //(data[x] >> 26) & 1 - trigger lost
2152  //(data[x] >> 25) & 1 - output buffer overflow
2153  //(data[x] >> 24) & 1 - tdc error
2154  //(data[x] >> 5) & 0xFFFF - word count
2155  tmpTimestamp= tmpTimestamp | ((data[x]) & 0x1f); // GEO bits of trailer include additional 5 bits of extended trigger time
2156  // GH Handle wraparound
2157  if (tmpTimestamp < lasttimestamp) { // Assume this means you wrapped around
2158  wraparoundcounter++; // How many times it wrapped around
2159  countsbetweenwraps=0; // Reset wraparound counter
2160  }
2161  lasttimestamp=tmpTimestamp; // so far so good
2162  ts = static_cast<Long64_t>(lasttimestamp); // start with 32 bits
2163  ts += static_cast<Long64_t>(0x100000000)*static_cast<Long64_t>(wraparoundcounter); // add wrap around
2164  ts = ts * static_cast<Long64_t>(5); // multiply by 5
2165  ts = ts >> 1; // divide by 2
2166  // And now that we've actually done all this:
2167  // Check if there's a somewhat valid timestamp from an ADC
2168  // the && 0 at the end suppresses the xfer
2169  if ( (event->GetSerialNumber()==xfermidsn) && (event->GetTimeStamp()==xfermidts)) { // Valid data from prior MADC bank
2170  eventFrag->SetTimeStamp(xferhfts);
2171  } else {
2172  eventFrag->SetTimeStamp(ts);
2173  }
2174  // got all the data, so now we can loop over the hits and write them
2175  if(addresses.size() != charges.size()) {
2176  std::cout<<"Something went horribly wrong, the number of addresses read "<<addresses.size()<<" doesn't match the number of charges read "<<charges.size()<<std::endl;
2177  return 0;
2178  }
2179  for(size_t i = 0; i < addresses.size(); ++i) {
2180  size_t duped = 0;
2181  size_t ii;
2182  if (i>0) {
2183  for (ii=0; ii<i; ii++) {
2184  if (addresses[i]==addresses[ii]) {
2185  duped++;
2186  }
2187  }
2188  }
2189  if (duped==0) {
2190  eventFrag->SetAddress(addresses[i]);
2191  eventFrag->SetCharge(static_cast<Int_t>(charges[i]));
2192  Push(fGoodOutputQueues, std::make_shared<TFragment>(*eventFrag));
2193  ++numFragsFound;
2194  }
2195  }
2196 
2197  // clear the old data
2198  addresses.clear();
2199  charges.clear();
2200  tmpTimestamp = 0;
2201  tmpAddress = 0;
2202  break;
2203  default:
2204  TParsingDiagnostics::Get()->BadFragment(13); // hard-coded 13 for TDC for now
2207  failedWord = x;
2208  } else {
2209  multipleErrors = true;
2210  }
2211  Push(*fBadOutputQueue, std::make_shared<TBadFragment>(*eventFrag, data, size, failedWord, multipleErrors));
2212  break;
2213 
2214  }
2215  }
2216  return numFragsFound;
2217 }
2218 
bool IgnoreMissingChannel() const
Definition: TGRSIOptions.h:114
bool SetGRIFChannelTriggerId(uint32_t, const std::shared_ptr< TFragment > &)
static TChannel * GetChannel(unsigned int temp_address, bool warn=false)
Definition: TChannel.cxx:340
bool SetGRIFTimeStampLow(uint32_t, const std::shared_ptr< TFragment > &)
bool fNoWaveforms
The flag to turn wave_forms on or off.
Definition: TDataParser.h:93
bool SetGRIFPsd(uint32_t, const std::shared_ptr< TFragment > &)
#define RED
Definition: Globals.h:8
static uint32_t wraparoundcounter
#define DRED
Definition: Globals.h:17
static Long64_t xferhfts
#define RESET_COLOR
Definition: Globals.h:4
void SetTIGWave(uint32_t, const std::shared_ptr< TFragment > &)
bool fFragmentHasWaveform
Definition: TDataParser.h:103
bool SetGRIFNetworkPacket(uint32_t, const std::shared_ptr< TFragment > &)
bool ReconstructTimeStamp() const
Definition: TGRSIOptions.h:74
int WordOffset() const
Definition: TGRSIOptions.h:92
bool SetGRIFPrimaryFilterPattern(uint32_t, const std::shared_ptr< TFragment > &, EBank)
static TGRSIOptions * Get(int argc=0, char **argv=nullptr)
Do not use!
bool SetGRIFCc(uint32_t, const std::shared_ptr< TFragment > &)
std::shared_ptr< ThreadsafeQueue< std::shared_ptr< const TBadFragment > > > fBadOutputQueue
Definition: TDataParser.h:89
bool SetScalerNetworkPacket(uint32_t, TScalerData *)
unsigned int xfermidsn
TFragmentMap fFragmentMap
Class that holds a map of fragments per address, takes care of calculating charges for GRF4 banks...
Definition: TDataParser.h:105
void SetScaler(size_t index, UInt_t scaler)
Definition: TScaler.h:49
int GriffinDataToPPGEvent(uint32_t *data, int size, unsigned int midasSerialNumber=0, time_t midasTime=0)
int RFScalerToFragment(uint32_t *data, const int size, const std::shared_ptr< TFragment > &frag)
void GoodFragment(const std::shared_ptr< const TFragment > &)
static TDeadtimeScalerQueue * Get()
void SetTIGAddress(uint32_t, const std::shared_ptr< TFragment > &)
int EmmaTdcDataToFragment(uint32_t *data, const int size, std::shared_ptr< TMidasEvent > &event)
void SetOldPPG(EPpgPattern oldPpg)
Definition: TPPG.h:82
bool SetGRIFDeadTime(uint32_t, const std::shared_ptr< TFragment > &)
int TigressDataToFragment(uint32_t *data, int size, std::shared_ptr< TMidasEvent > &event)
#define DYELLOW
Definition: Globals.h:15
static TRunInfo * Get(bool verbose=false)
Definition: TSingleton.h:34
unsigned long fLastTriggerId
The last Trigged ID in the raw File.
Definition: TDataParser.h:99
bool SetPPGLowTimeStamp(uint32_t, TPPGData *)
std::string hex(T val, int width=-1)
Definition: Globals.h:134
void SetNetworkPacketId(UInt_t networkId)
Definition: TScaler.h:46
bool SetNewPPGPattern(uint32_t, TPPGData *)
static uint32_t lasttimestamp
const char * GetDigitizerTypeString() const
Definition: TChannel.h:170
void SetHighTimeStamp(UInt_t highTime)
Definition: TScaler.h:48
void SetHighTimeStamp(UInt_t highTime)
Definition: TPPG.h:64
bool SetPPGHighTimeStamp(uint32_t, TPPGData *)
void SetNewPPG(EPpgPattern newPpg)
Definition: TPPG.h:69
int GriffinDataToFragment(uint32_t *data, int size, EBank bank, unsigned int midasSerialNumber=0, time_t midasTime=0)
int CaenPhaToFragment(uint32_t *data, int size, std::shared_ptr< TMidasEvent > &event)
std::shared_ptr< ThreadsafeQueue< std::shared_ptr< TEpicsFrag > > > fScalerOutputQueue
Definition: TDataParser.h:90
bool SetGRIFPrimaryFilterId(uint32_t, const std::shared_ptr< TFragment > &)
std::map< UInt_t, Long64_t > fLastTimeStampMap
Definition: TDataParser.h:107
bool SetTIGTriggerID(uint32_t, const std::shared_ptr< TFragment > &)
static time_t xfermidts
TChannel * fChannel
Definition: TDataParser.h:95
int EPIXToScalar(float *data, int size, unsigned int midasSerialNumber=0, time_t midasTime=0)
void SetAddress(UInt_t address)
Definition: TScaler.h:45
TXMLNode * FindPath(const char *path, TXMLNode *node=nullptr)
Definition: TXMLOdb.cxx:77
void AddData(TPPGData *pat)
Definition: TPPG.cxx:119
void Add(TScalerData *)
bool SetPPGNetworkPacket(uint32_t, TPPGData *)
const Double_t s
int CaenPsdToFragment(uint32_t *data, int size, std::shared_ptr< TMidasEvent > &event)
std::vector< std::shared_ptr< ThreadsafeQueue< std::shared_ptr< const TFragment > > > > fGoodOutputQueues
Definition: TDataParser.h:88
int ProcessGriffin(uint32_t *data, const int &size, const EBank &bank, std::shared_ptr< TMidasEvent > &event)
EDataParserState fState
static TRateScalerQueue * Get()
bool SetScalerHighTimeStamp(uint32_t, TScalerData *, int &)
void SetLowTimeStamp(UInt_t lowTime)
Definition: TPPG.h:59
static std::string GetEpicsVariableName(const int &i)
Definition: TEpicsFrag.cxx:77
int GriffinDataToScalerEvent(uint32_t *data, int address)
void SetNetworkPacketId(UInt_t packet)
Definition: TPPG.h:95
Definition: TPPG.h:47
void SetTIGCharge(uint32_t, const std::shared_ptr< TFragment > &)
bool SetGRIFHeader(uint32_t, const std::shared_ptr< TFragment > &, EBank)
const unsigned long fMaxTriggerId
The last trigger ID Called.
Definition: TDataParser.h:97
bool SetTIGTimeStamp(uint32_t *, const std::shared_ptr< TFragment > &)
void SetTIGLed(uint32_t, const std::shared_ptr< TFragment > &)
UInt_t GetLowTimeStamp() const
Definition: TScaler.h:61
static uint32_t countsbetweenwraps
bool SetGRIFWaveForm(uint32_t, const std::shared_ptr< TFragment > &)
bool SetScalerLowTimeStamp(uint32_t, TScalerData *)
void BadFragment(Short_t detType)
bool Add(std::shared_ptr< TFragment >, std::vector< Int_t >, std::vector< Short_t >)
static TGRSIOptions * fOptions
Static pointer to TGRSIOptions, gets set on the first call of GriffinDataToFragment.
Definition: TDataParser.h:109
#define BLUE
Definition: Globals.h:5
void SetLowTimeStamp(UInt_t lowTime)
Definition: TScaler.h:47
bool fIgnoreMissingChannel
flag that&#39;s set to TGRSIOptions::IgnoreMissingChannel
MIDAS event.
Definition: TMidasEvent.h:35
void Add(TScalerData *)
const char * what() const noexcept override
int Process(std::shared_ptr< TRawEvent >) override
bool SuppressErrors() const
Definition: TGRSIOptions.h:73
void SetTIGCfd(uint32_t, const std::shared_ptr< TFragment > &)
bool fRecordDiag
The flag to turn on diagnostics recording.
Definition: TDataParser.h:94
bool SetScalerValue(int, uint32_t, TScalerData *)
int SetBankList()
create the list of data banks, return number of banks
int EmmaMadcDataToFragment(uint32_t *data, const int size, std::shared_ptr< TMidasEvent > &event)
#define DBLUE
Definition: Globals.h:14
bool SetOldPPGPattern(uint32_t, TPPGData *)
void Push(ThreadsafeQueue< std::shared_ptr< const TBadFragment >> &queue, const std::shared_ptr< TBadFragment > &frag)
Definition: TDataParser.cxx:72