GammaWare  Head Version for release 0.9
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
ReadMezzAFP.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  * Copyright (C) 2004 by Olivier Stezowski *
3  * stezow(AT)ipnl.in2p3.fr *
4  * *
5  * This program is free software; you can redistribute it and/or modify *
6  * it under the terms of the GNU General Public License as published by *
7  * the Free Software Foundation; either version 2 of the License, or *
8  * (at your option) any later version. *
9  * *
10  * This program is distributed in the hope that it will be useful, *
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13  * GNU General Public License for more details. *
14  * *
15  * You should have received a copy of the GNU General Public License *
16  * along with this program; if not, write to the *
17  * Free Software Foundation, Inc., *
18  * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
19  ***************************************************************************/
20 
23 #include <iostream>
24 #include <iomanip>
25 #include <fstream>
26 #include <sstream>
27 #include <cstdio>
28 #include <vector>
29 
30 #include "BufferIO.h"
31 
32 #include "BashColor.h"
33 #include "ReadMezzAFP.h"
34 
35 using namespace ADF;
36 
39  fSourceOfFrames(aMByte,ConfAgent::kRead),
40  fPath("./"),
41  fBaseForName("AFP_"),
42  fCurrentFile(0x0),
43  fCurrentFileNumber(0u),
44  fMaxSize(kMaxInt_t),
45  fConfMode(-1),
46  fListOfFile(),
47  fEndOfFrame("EndOfFrame"),
48  FirstTimeStamp(0),
49  LastTimeStamp(0),
50  fFrameCrystal_Out(NULL),
51  fTrigger("data:crystal"),
52  fdebug(false),
53  fBashColor(new BashColor()),
54  fUseKeyFilter(false),
55  fLastKeyIsRead(false),
56  fNEvts(0),
57  fNIgnoredEvts(0),
58  fBitFlipMezzLength(0),
59  fBitFlipTraceLength(0),
60  fBitFlipSegId(0),
61  fBitFlipTS(0),
62  fCrystalName(""),
63  TotalEntryFileSize(0),
64  ReadEntryFileSize(0),
65  LastReadEntryFileSize(0)
66 {
67  if(fdebug) std::cout<<"\E[31;1m"<<"Construct in"<<"\E[m"<<std::endl;
68 
69  Log.GetProcessName() = "ReadMezzAFP"; GetFrameIO().SetName("ReadMezzAFP");
70 
71  // to be sure unknown frames are written in the ouput
72  GetFrameIO().SetModel(ConfAgent::kSafe);
73  // to protect writings in the source of frames
74  fSourceOfFrames.SetModeIO(ConfAgent::kRead);
75 
76  // the input datablock is owned by BasicAFP
77  GetFrameIO().Attach(&fSourceOfFrames,0x0);
78  fListOfFile.clear();
79 
80  if(fdebug) std::cout<<"\E[31;1m"<<"Construct out"<<"\E[m"<<std::endl;
81 }
82 
84 {
85  // in principle not needed ... just in case reset it has not been called by narval
86  unsigned int error = 0u; process_reset(&error) ;
87 
88  for(int nn = 0; nn < kNSG; nn++ )
89  delete [] SegmentTraces[nn];
90  for(int nn = 0; nn < kNCC; nn++ )
91  delete [] CoreTraces[nn];
92 }
93 
95 {
96  Log.SetProcessMethod("NewFile");
97  bool ok = false;
98  NewCrystal = false;
99 
100  if ( fConfMode == -1 ) // not properly initialised
101  return ok;
102 
103  // close the current file
104  if ( fCurrentFile )
105  ::fclose(fCurrentFile);
106  fCurrentFile = 0x0;
107 
108  if ( fConfMode == 0 ) {
109  // open the first file to be ready to be run
110  std::string tmp = fPath;
111  if ( tmp.size() > 0 && !(tmp.at(tmp.size()-1) == '/') )
112  tmp += '/';
113 
114  // try to open the next file
115  std::ostringstream filename;
116  filename << tmp << fBaseForName
117  << std::setfill('0') << std::setw(4) << fCurrentFileNumber++;
118 
119  fCurrentFile = ::fopen(filename.str().data(),"rb");
120  if ( fCurrentFile != 0x0 ) {
121  Log << "A new input file has just been open "
122  << filename.str() << nline;
123  fSourceOfFrames.SetFile
124  (fCurrentFile,fMaxSize);
126  (BaseFrameIO::kIdle);
127  ok = true;
128  }
129  else {
130  Log << warning << "Cannot open file "
131  << filename.str()
132  << nline;
133  GetFrameIO().SetStatus(BaseFrameIO::kFinished);
134  }
135  }
136  else {
137  // try to open the next file
138  while ( fCurrentFileNumber < fListOfFile.size() ) {
139 
140  fCurrentFile = ::fopen(fListOfFile[fCurrentFileNumber].data(),"rb");
141  if ( fCurrentFile == 0x0 ) {
142  Log << warning << "File "
143  << fListOfFile[fCurrentFileNumber]
144  << " is not a valid file "
145  << nline ;
146 
147  fCurrentFileNumber++;
148  continue;
149  }
150  Log << info << "A new input file has just been open "
151  << fListOfFile[fCurrentFileNumber]
152  << nline;
153  fSourceOfFrames.SetFile(fCurrentFile,fMaxSize);
154  GetFrameIO().SetStatus(BaseFrameIO::kIdle);
155  ok = true;
156 
157  std::vector<std::string> token2 = split(fListOfFile[fCurrentFileNumber],'/');
158  fCrystalName = token2[token2.size()-2];
159 
160  if(fCurrentFileNumber > 0)
161  {
162  std::vector<std::string> token = split(fListOfFile[fCurrentFileNumber-1],'/');
163  std::string previouscrystal = token[token.size()-2];
164 
165  if(previouscrystal != fCrystalName) NewCrystal = true;
166 
167  fCrystalName = previouscrystal;
168  }
169 
170  fCurrentFileNumber++;
171 
172  break;
173  }
174  if ( !ok )
175  GetFrameIO().SetStatus(BaseFrameIO::kFinished);
176  }
177  // send the log collected in this method
178  Log << dolog;
179 
180  return ok;
181 }
182 
183 void ReadMezzAFP::process_config (const char *directory_path, unsigned int *error_code)
184 {
185  // first init narval and ADF stuff (if required)
186  NarvalInterface::process_config(directory_path,error_code);
187 
188  if ( (*error_code) == 0u ) { // now init your stuff
189  }
190 }
191 
193 {
194  if(fdebug) std::cout<<"\E[31;1m"<<"ProcessBlock in"<<"\E[m"<<std::endl;
195 
196  // attach the input/output buffer to the FrameIO system
197 
198  GetFrameIO().Attach(NULL, &out);
199 
200  // start the processing
201 
202  Frame *frame_out = fFrameCrystal_Out->GetFrame();
203  CrystalInterface *cdata = GetDataPointer<CrystalInterface>(frame_out);
204 
205  frame_out->Write();
206 
207  unsigned int EventLenght = frame_out->GetLength();
208 
209  while(out.Reserve(EventLenght,true))
210  {
211  frame_out->Reset();
212 
213  int ok = ReadEvent();
214 
215  if(ok!=1)
216  {
217  if(ok==2) continue; //bad event
218  //else end of file
219  if(NewFile())
220  {
221  if(NewCrystal)
222  {
223  PrintStats();
224  ResetStats();
225  }
226  continue;
227  }
228  else
229  {
230  std::cout<<std::endl;
231  PrintStats();
232  out.SetEoB(true);
233  break;
234  }
235  }
236 
237  if(fLastKeyIsRead)
238  {
239  out.SetEoB(true);
240  break;
241  }
242 
243  fNEvts++;
244 
245  if( fUseKeyFilter)
246  {
247  if(evnumber == fNextEvtNbr)
248  {
249  // fBashColor->SetInfoOut();
250  // std::cout<<"Evt Number = "<<evnumber<<" ; Ref Evt Nbr = "<<fNextEvtNbr<<std::endl;
251  // std::cout<<"TimeStamp = "<<timestamp<<" ; Ref TimeStamp = "<<fNextTS<<std::endl;
252  // fBashColor->ResetColor();
253  NextKeyToFind();
254  }
255  else
256  {
257  // fBashColor->SetWarningOut();
258  // std::cout<<"Evt Number = "<<evnumber<<" ignored, looking for Evt Nbr = "<<fNextEvtNbr<<std::endl;
259  // std::cout<<"TimeStamp = "<<timestamp<<" ignored, looking for TimeStamp = "<<fNextTS<<std::endl;
260  // fBashColor->ResetColor();
261  fNIgnoredEvts++;
262  continue;
263  }
264  }
265 
266  for(int i = 0; i < kNSG; i++) {
267  segMezz = cdata->GetSegment(i);
269  segMezz->SetE(SegE[i]);
271  segMezz->SetID(SegID[i]);
272  }
273  for(int i = 0; i < kNCC; i++) {
274  coreMezz = cdata->GetCore(i);
276  coreMezz->SetE(CoreE[i]);
278  coreMezz->SetID(CoreID[i]);
279  coreMezz->SetT(0);
280  }
281 
282  // Insert timestamp and event number
283  ( ( AgataKey * ) frame_out->GetKey() )->SetTimeStamp( timestamp );
284  ( ( AgataKey * ) frame_out->GetKey() )->SetEventNumber( evnumber );
285  crystal_status = 0; // all "normal" events are good
286 
287  frame_out->Write();
288 
289  fTrigger.Fired(true);
290  GetFrameIO().Record();
291  }
292 
293  double Ratio = ((double)ReadEntryFileSize)/((double)TotalEntryFileSize)*100.;
294  double LastRatio = ((double)LastReadEntryFileSize)/((double)TotalEntryFileSize)*100.;
295 
296  std::ostringstream toto;
297  toto<<TotalEntryFileSize;
298  int NDigits = toto.str().length();
299 
300  if(((int)Ratio) != ((int)LastRatio))
301  std::cout<<"\r"<<"Analysis progress : "<<std::setw(3)<<(int)(Ratio+0.5)<<" %"<<" ("<<std::setw(NDigits)<<ReadEntryFileSize<<"/"<<std::setw(NDigits)<<TotalEntryFileSize<<" bytes)"<<std::flush;
302 
303 
304  LastReadEntryFileSize = ReadEntryFileSize;
305 
306  GetFrameIO().Detach(NULL, &out);
307 
308  if(fdebug) std::cout<<"\E[31;1m"<<"ProcessBlock out"<<"\E[m"<<std::endl;
309 
310  if ( GetFrameIO().GetStatus() == BaseFrameIO::kFinished || fLastKeyIsRead)
311  return 1u;
312  else return 0u;
313 }
314 
315 void ReadMezzAFP::process_initialise (unsigned int *error_code)
316 {
317  if(fdebug) std::cout<<"\E[31;1m"<<"process_initialise in"<<"\E[m"<<std::endl;
318 
319  std::string tmp, option;
320 
321  *error_code = 0u; Log.ClearMessage(); Log.SetProcessMethod("process_initialise");
322 
323  // read an input file to get the base filename and the path
324  std::string conffile = GetConfPath();
325  conffile += "ReadMezzAFP.conf";
326 
327  fCurrentFileNumber = 0u;
328 
329  std::ifstream filein(conffile.data());
330  if ( filein.is_open() == true ) {
331  getline(filein,tmp);
332  tmp += " ";
333  while ( filein.good() && !filein.eof() ) { // read input stream line by line
334  if ( tmp[0] == '#' ) {
335  getline(filein,tmp);
336  tmp += " ";
337  continue;
338  } // this line is a comment
339 
340  std::istringstream decode(tmp);
341 
342  if( tmp[0] == 'b' ){ // to emulate a BasicAFP
343 
344  std::string pathforfiles, basename;
345  unsigned int starting_number;
346  decode >> option >> pathforfiles >> basename >> starting_number;
347 
348  if ( decode.good() ) {
349 
350  fPath = pathforfiles;
351  fBaseForName = basename;
352  fCurrentFileNumber = starting_number;
353 
354  fConfMode = 0;
355  }
356  }
357  if( tmp[0] == 'l' ) { // the .conf file contains the list of file to be read
358 
359  std::string filename;
360  decode >> option >> filename;
361  if( decode.good() )
362  {
363  std::vector<std::string> token = split(filename,'/');
364 
365  fPath = filename;
366  replace(fPath,token[token.size()-1],"");
367 
368  fListOfFile.push_back(filename);
369  }
370 
371  fConfMode = 1;
372  }
373  if( tmp[0] == 'r' ) { // the .conf contains a range of files to be read
374  unsigned int starting_number, ending_number;
375  std::string pathforfiles, basename;
376  decode >> option >> pathforfiles >> basename >> starting_number >> ending_number;
377  if( decode.good() && starting_number < ending_number ){
378 
379  fPath = pathforfiles;
380  fBaseForName = basename;
381 
382  for( unsigned int number = starting_number; number <= ending_number; number++ ){
383  std::ostringstream osfilename;
384  osfilename << pathforfiles << basename << std::setfill('0') << std::setw(4) << number;
385  fListOfFile.push_back(osfilename.str());
386  }
387  }
388  fConfMode = 2;
389  }
390  if( tmp[0] == 'f' ) { // the .conf contains a key filter
391  std::string pathforfilter;
392  decode >> option >> pathforfilter;
393  if(decode.good()){
394  fKeyFilterFile = 0x0;
395  fKeyFilterFile = ::fopen(pathforfilter.data(),"rb");
396  if(fKeyFilterFile == 0x0)
397  {
398  fBashColor->SetErrorOut();
399  std::cout<<"Key filter file not found, key filter ignored !"<<std::endl;
400  fBashColor->ResetColor();
401  }
402  else
403  {
404  fBashColor->SetInfoOut();
405  std::cout<<"Key filter file : "<<pathforfilter<<" will be used !"<<std::endl;
406  fBashColor->ResetColor();
407 
408  ::fseek(fKeyFilterFile, 0, SEEK_END);
409  long size = ::ftell(fKeyFilterFile);
410 
411  ::rewind(fKeyFilterFile);
412 
413  fKeyFilterBuffer = new BufferIO(size);
414 
417 
418  const ADF::FactoryItem item("Agata","data:psa",ADF::Version(4,0));
419 
420  fKeyToLink = (AgataKey*)MainKeyFactory::theMainFactory().New(item);
421 
422  NextKeyToFind();
423 
424  fUseKeyFilter = true;
425  }
426  }
427  }
428  getline(filein,tmp);
429  tmp += " ";
430  }
431  }
432  else
433  {
434  std::cout<<"\E[31;1m"<<conffile.data()<<" not found !"<<"\E[m"<<std::endl;
435  *error_code = 1u;
436  }
437  filein.close();
438 
439  switch (fConfMode) {
440  case -1:
441  *error_code = 1u;
442  Log << error << "Not properly initialised" << nline ;
443  break;
444  case 0:
445  Log << info << "Init in BasicAFP mode" << nline ;
446  break;
447  case 1:
448  for(unsigned int i=0 ; i<fListOfFile.size() ; i++)
449  {
450  std::ifstream afile(fListOfFile[i].data(), std::ios_base::binary);
451  afile.seekg( 0 , std::ios_base::end );
452  unsigned long size = afile.tellg() ;
453  afile.close();
454  TotalEntryFileSize += size;
455  }
456  case 2:
457  Log << info << "List of file to be read is " << fListOfFile.size() << nline ;
458  break;
459  default:
460  break;
461  }
462 
463  // Read the crystal producer conf file
464 
465  std::string ConfFilePath = fPath;
466 
467  std::vector<std::string> token = split(ConfFilePath,'/');
468 
469  replace(ConfFilePath,(std::string)"/" + token[token.size()-3] + "/","/Conf/");
470 
471  ConfFilePath += "CrystalProducer.conf";
472 
473  std::ifstream ProdConfFile(ConfFilePath.data());
474  if ( ProdConfFile.is_open() == true )
475  {
476  std::string Line;
477 
478  while(ProdConfFile)
479  {
480  getline(ProdConfFile,Line);
481 
482  std::vector<std::string> token = split(Line,' ');
483 
484  unsigned int val;
485  std::istringstream ( token[token.size()-1] ) >> val;
486 
487  if(contains(Line,"TraceLength")) fTraceLengthRaw = (unsigned int) val;
488  if(contains(Line,"CrystalID")) crystal_id = (unsigned int) val;
489  }
490  }
491  else
492  {
493  std::cout<<"\E[31;1m"<<ConfFilePath.data()<<" not found !"<<"\E[m"<<std::endl;
494  *error_code = 1u;
495  return;
496  }
497 
499 
500  fFrameCrystal_Out = fTrigger.SetOutputFrame("Agata", "data:crystal");
501 
502  if(fFrameCrystal_Out) {
503  // link named items with local variables.
504  GObject *glob = GetDataPointer<CrystalInterface>(fFrameCrystal_Out)->Global();
505  glob->LinkItem("CrystalID", &crystal_id);
506  glob->LinkItem("CrystalStatus", &crystal_status);
507  }
508 
510 
511  GetFrameIO().SetModel(ConfAgent::kSafe);
512 
513  // initialise the internal structures
514 
515  evnumber = 0;
516  timestamp = 0;
517 
518  for(int atseg = 0; atseg < kNSG; atseg++) {
519  SegmentTraces[atseg] = new unsigned short[fTraceLengthRaw];
520  memset(SegmentTraces[atseg], 0, sizeof(unsigned short)*fTraceLengthRaw);
521  SegE[atseg] = 0;
522  SegID[atseg] = 0;
523  SegStatus[atseg] = 0;
524  }
525  for(int atcore = 0; atcore < kNCC; atcore++) {
526  CoreTraces[atcore] = new unsigned short[fTraceLengthRaw];
527  memset(CoreTraces[atcore], 0, sizeof(unsigned short)*fTraceLengthRaw);
528  CoreE[atcore] = 0;
529  CoreID[atcore] = 0;
530  CoreStatus[atcore] = 0;
531  }
532 
533  // open the first file
534  if ( *error_code == 0u )
535  if ( !NewFile() )
536  *error_code = 2u;
537 
538  Log << dolog;
539 
540  if(fdebug) std::cout<<"\E[31;1m"<<"process_initialise out"<<"\E[m"<<std::endl;
541 }
542 
543 
544 void ReadMezzAFP::process_reset (unsigned int *error_code)
545 {
546  *error_code = 0u;
547  Log.ClearMessage(); Log.SetProcessMethod("process_reset");
548 
549  if ( fCurrentFile )
550  ::fclose(fCurrentFile);
551  fCurrentFileNumber = 0u;
552  fConfMode = -1;
553 
554  GetFrameIO().Print( Log() );
555 
556  Log << dolog;
557 }
558 
559 std::vector<std::string> ReadMezzAFP::split(std::string s, char c)
560 {
561  const char* str = s.c_str();
562 
563  std::vector<std::string> result;
564 
565  do
566  {
567  const char *begin = str;
568 
569  while(*str != c && *str)
570  str++;
571 
572  result.push_back(std::string(begin,str));
573  }
574  while (0 != *str++);
575 
576  return result;
577 }
578 
579 bool ReadMezzAFP::replace(std::string& str, const std::string& from, const std::string& to)
580 {
581  size_t start_pos = str.find(from);
582  if(start_pos == std::string::npos) return false;
583  str.replace(start_pos,from.length(), to);
584  return true;
585 }
586 
587 
588 bool ReadMezzAFP::contains(std::string s1, std::string s2)
589 {
590  if(s1.find(s2) != std::string::npos) return true;
591  else return false;
592 }
593 
594 unsigned int ReadMezzAFP::uncompress_single_trace_AB(unsigned char* compr, unsigned int csize, unsigned short* trace)
595 {
596  unsigned char* compressed = compr;
597  unsigned char* c_end = compr + csize;
598 
599  // first trace point is verbatim (little endian)
600  unsigned char p1 = *compressed++, p2 = *compressed++;
601  unsigned short ref = p2<<8 | p1;
602  trace[0] = ref^0x2000;
603 
604  unsigned int midx;
605  for(midx=1; compressed<c_end && midx<fTraceLengthRaw; ++midx) {
606  const unsigned char packed = *compressed++;
607  if( (packed & 0x80) == 0 ) {
608  // three trace points as two differences
609  const unsigned char p2 = *compressed++;
610  const unsigned short packed2 = packed<<8 | p2;
611  const int diff1 = ((packed2>>10) & 0x1F) - 15;
612  const int diff2 = ((packed2>> 5) & 0x1F) - 15;
613  const int diff3 = ( packed2 & 0x1F) - 15;
614  ref += diff1;
615  trace[midx++] = ref^0x2000;
616  ref += diff2;
617  trace[midx++] = ref^0x2000;
618  ref += diff3;
619  } else if( (packed & 0xC0) == 0xC0 ) {
620  if( compressed>=c_end )
621  return false;
622  // one trace point as copy
623  ref = (packed&0x3F)<<8 | *compressed++;
624  } else {
625  // one trace point as difference to previous
626  const int diff1 = (packed & 0x3F) + MIN_1x6;
627  ref += diff1;
628  }
629  trace[midx] = ref^0x2000;
630  }
631  return midx;
632 }
633 
635 {
636  int lenChanData; // MAX number of samples
637  int lenChanTotal; // lenChanHeader + lenChanData
638  int lenMezzTotal; // lenMezzHeader + lenChanTotaln*Chan
639  int NChan = 6;
640 
641  lenChanData = fTraceLengthRaw;
642  lenChanTotal = mezzanineChanHeader + lenChanData;
643  lenMezzTotal = mezzanineMezzHeader + lenChanTotal*NChan;
644 
645  std::vector < std::pair < unsigned long long, unsigned short > > ListOfTS;
646 
647  for(int mezz=0 ; mezz<7 ; mezz++)
648  {
649  unsigned short* BuffChannHead = new unsigned short[mezzanineMezzHeader];
650  memset(BuffChannHead, 0, sizeof(unsigned short)*mezzanineMezzHeader);
651 
652  fread((void *)BuffChannHead, sizeof(unsigned short), mezzanineMezzHeader, fCurrentFile);
653  ReadEntryFileSize += mezzanineMezzHeader*sizeof(unsigned short);
654 
655  unsigned short SlotId = BuffChannHead[0] & 0x0F ;
656  evnumber = (unsigned int) BuffChannHead[1] | (unsigned int) BuffChannHead[2] << 16;
657  timestamp = (unsigned long long)BuffChannHead[3] | (unsigned long long)BuffChannHead[4] << 16 | (unsigned long long)BuffChannHead[5] << 32;
658 
659  unsigned short TraceLen = BuffChannHead[6];
660  unsigned short MezzLen= BuffChannHead[7];
661  unsigned short DomainId = BuffChannHead[8] & 0xFF;
662  unsigned int ActMezzLen = BuffChannHead[15];
663 
665  bool alreadyseen = false;
666 
667  for(unsigned int itest=0 ; itest<ListOfTS.size() ; itest++)
668  {
669  std::pair < unsigned long long, unsigned short > *a_pair = &ListOfTS[itest];
670  if(timestamp == a_pair->first)
671  {
672  a_pair->second = a_pair->second+1;
673  alreadyseen = true;
674  }
675  }
676 
677  if(!alreadyseen)
678  {
679  std::pair < unsigned long long, unsigned short > a_pair;
680  a_pair.first = timestamp;
681  a_pair.second = 1;
682 
683  ListOfTS.push_back(a_pair);
684  }
685 
686  if(::feof(fCurrentFile))
687  {
688  if(SlotId != 0 && fdebug)
689  {
690  fBashColor->SetWarningOut();
691  std::cout<<"File stoped after reading the header of mezzanine ID : "<<SlotId<<std::endl;
692  std::cout<<"Timestamp = "<<timestamp<<std::endl;
693  std::cout<<"Event number = "<<evnumber<<std::endl;
694  fBashColor->ResetColor();
695  }
696 
697  delete [] BuffChannHead;
698  return 0;
699  }
700 
701  if(SlotId<1 || SlotId>7)
702  {
703  std::cout<<"\E[31;1m"<<"Bad Header, SlotID = "<<SlotId<<"\E[m"<<std::endl;
704  }
705 
706  if(TraceLen!=fTraceLengthRaw)
707  {
708  fBitFlipTraceLength++;
709 
710  if(fdebug)
711  {
712  unsigned int NormalTraceLength = 100;
713  std::cout<<"Normal TraceLength "<<std::setw(4)<<NormalTraceLength<<std::setw(6)<<std::hex<<NormalTraceLength<<std::dec<<std::setw(20)<<ConvertToBinary(NormalTraceLength)<<std::endl;
714  std::cout<<"Actual TraceLength "<<std::setw(4)<<TraceLen<<std::setw(6)<<std::hex<<TraceLen<<std::dec<<std::setw(20)<<ConvertToBinary(TraceLen)<<std::endl;
715 
716  std::cout<<"\E[31;1m"<<"Number of samples different from configuration file"<<"\E[m"<<std::endl;
717  std::cout<<"TraceLen = "<<TraceLen<<std::endl;
718  }
719  }
720 
721  // read and decompress
722  int toread = ActMezzLen;
723 
724  if(toread==0) //not compressed
725  {
726  toread = MezzLen;
727  if(toread == 0) // initial format did not contain total length
728  toread = (TraceLen+mezzanineChanHeader)*NChan + mezzanineMezzHeader;
729  }
730 
731  unsigned short *compBuffer = new unsigned short[toread];
732  memset(compBuffer, 0, sizeof(unsigned short)*toread);
733 
734  toread -= mezzanineMezzHeader;
735 
736  fread(compBuffer, sizeof(unsigned short), toread, fCurrentFile);
737  ReadEntryFileSize += toread*sizeof(unsigned short);
738 
739  if(::feof(fCurrentFile))
740  {
741  if(SlotId != 7 && fdebug)
742  {
743  fBashColor->SetWarningOut();
744  std::cout<<"File stoped after reading the traces of mezzanine ID : "<<SlotId<<std::endl;
745  std::cout<<"Timestamp = "<<timestamp<<std::endl;
746  std::cout<<"Event number = "<<evnumber<<std::endl;
747  fBashColor->ResetColor();
748  }
749  delete [] BuffChannHead;
750  delete [] compBuffer;
751  return 0;
752  }
753 
754  int numchan = (MezzLen-mezzanineMezzHeader)/(TraceLen+mezzanineChanHeader);
755 
756  if(numchan!=NChan)
757  {
758  fBitFlipMezzLength++;
759 
760  if(fdebug)
761  {
762  unsigned int NormalLength = 664;
763  std::cout<<"Normal MezzLength "<<std::setw(4)<<NormalLength<<std::setw(6)<<std::hex<<NormalLength<<std::dec<<std::setw(20)<<ConvertToBinary(NormalLength)<<std::endl;
764  std::cout<<"Actual MezzLength "<<std::setw(4)<<MezzLen<<std::setw(6)<<std::hex<<MezzLen<<std::dec<<std::setw(20)<<ConvertToBinary(MezzLen)<<std::endl;
765 
766  fBashColor->SetWarningOut();
767  std::cout<<"\E[31;1m"<<"Number of channels non equal to "<<NChan<<"\E[m"<<std::endl;
768  std::cout<<"numchan = "<<numchan<<std::endl;
769  fBashColor->ResetColor();
770  }
771  }
772 
773  unsigned short* dbuffer = new unsigned short[lenMezzTotal];
774  memset(dbuffer, 0, sizeof(unsigned short)*lenMezzTotal);
775  unsigned int PosInBuff=0;
776 
777  memcpy(dbuffer, BuffChannHead, sizeof(unsigned short)*mezzanineMezzHeader);
778 
779  delete [] BuffChannHead;
780 
781  unsigned short *pD = dbuffer + mezzanineMezzHeader;
782  unsigned short *pC = compBuffer;
783 
784  dbuffer += mezzanineMezzHeader;
785  PosInBuff += mezzanineMezzHeader;
786 
787  for(int nn = 0; nn < NChan; nn++) {
788 
789  memcpy(pD, pC, sizeof(unsigned short)*mezzanineChanHeader);
790  pC += mezzanineChanHeader;
791  pD += mezzanineChanHeader;
792  unsigned int csize = pD[-1];
793  unsigned int ctype = pD[-2] & 0xF;
794  int ll = 0;
795 
796  if(ctype==0) //no compression
797  {
798  memcpy(dbuffer, compBuffer, sizeof(unsigned short)*toread);
799  break;
800  }
801  else if(ctype==1)
802  {
803  ll = uncompress_single_trace_AB((unsigned char *)pC, 2*csize, pD);
804  }
805  else
806  {
807  std::cout<<"WARNING : Compression type unkown : "<<ctype<<std::endl;
808 
809  std::cout<<"Mezzanine Header :"<<std::endl;
810  std::cout<<"SlotId = "<<SlotId<<std::endl;
811  std::cout<<"EvNumb = "<<evnumber<<std::endl;
812  std::cout<<"Tstamp = "<<timestamp<<std::endl;
813  std::cout<<"TraceLen = "<<TraceLen<<std::endl;
814  std::cout<<"MezzLen = "<<MezzLen<<std::endl;
815  std::cout<<"DomainId = "<<DomainId<<std::endl;
816  std::cout<<"ActMezzLen = "<<ActMezzLen<<std::endl<<std::endl;
817  std::cout<<std::endl;
818 
819  delete [] compBuffer;
820  dbuffer -= PosInBuff;
821  delete [] dbuffer;
822 
823  return 2;
824  }
825  pD[-1] = 0; // remove compression tags
826  pD[-2] = 0;
827  pC += csize;;
828  pD += ll;
829  }
830 
831  if(fdebug)
832  {
833  std::cout<<"Mezzanine Header :"<<std::endl;
834  std::cout<<"SlotId = "<<SlotId<<std::endl;
835  std::cout<<"EvNumb = "<<evnumber<<std::endl;
836  std::cout<<"Tstamp = "<<timestamp<<std::endl;
837  std::cout<<"TraceLen = "<<TraceLen<<std::endl;
838  std::cout<<"MezzLen = "<<MezzLen<<std::endl;
839  std::cout<<"DomainId = "<<DomainId<<std::endl;
840  std::cout<<"ActMezzLen = "<<ActMezzLen<<std::endl<<std::endl;
841  std::cout<<std::endl;
842  }
843 
844  for(int i=0 ; i<NChan ; i++)
845  {
846  if(dbuffer[0] > 7) fBitFlipSegId++;
847 
848  int ID = dbuffer[0];// & 7; /// & 7 to put a mask only on the 3 first bits, to avoid bit flipping
849 
850  if(ID != i )
851  {
852  fBitFlipSegId++;
853  }
854 
855  ID = i;
856 
857  int ener32 = dbuffer[2];
858  ener32 = (ener32 << 16) | dbuffer[1];
859 
860  int SegId = (SlotId-2)*6+(5-ID);
861  if((SegId<0 || SegId >37) && SlotId>1)
862  {
863  std::cout<<std::endl;
864  std::cout<<"SegID = "<<SegId<<std::endl;
865  std::cout<<"SlotId = "<<SlotId<<std::endl;
866  std::cout<<"ID = "<<ID<<std::endl;
867  }
868 
869  float Ener = float(ener32)/(1<<16);
870  int Status = dbuffer[3];
871  int CompType = dbuffer[6];
872  int CompTraceLen = dbuffer[7];
873 
874  if(SlotId==1 && (ID==0 || ID==1))
875  {
876  CoreE[ID] = Ener;
877  CoreStatus[ID] = Status;
878  CoreID[ID] = ID;
879  }
880  else if(SlotId==1) {;}
881  else
882  {
883  SegE[SegId] = Ener;
884  SegStatus[SegId] = Status;
885  SegID[SegId] = SegId;
886  }
887 
888  if(fdebug)
889  {
890  if(SlotId==1 && !(ID==0 || ID==1)) break;
891 
892  fBashColor->SetInfoOut();
893  std::cout<<std::endl;
894  if(SlotId!=1)
895  {
896  std::cout<<"trace ID = "<<ID<<std::endl;
897  std::cout<<"Seg ID = "<<SegId<<std::endl;
898  }
899  else std::cout<<"core ID = "<<ID<<std::endl;
900  std::cout<<"Ener = "<<Ener<<std::endl;
901  std::cout<<"Status = "<<Status<<std::endl;
902  std::cout<<"CompType = "<<CompType<<std::endl;
903  std::cout<<"CompTraceLen = "<<CompTraceLen<<std::endl;
904  std::cout<<std::endl;
905  fBashColor->ResetColor();
906  }
907 
908  dbuffer += mezzanineChanHeader;
909  PosInBuff += mezzanineChanHeader;
910 
911  unsigned short tmp16;
912 
913  for(unsigned int j=0 ; j<fTraceLengthRaw ; j++)
914  {
915  tmp16 = dbuffer[j];
916  tmp16 &= 0x3FFF; // keep 14 bits
917  tmp16 ^= 0x2000; // reverse highest ADC bit
918  // tmp16 = 0x3FFF - tmp16; // change sign
919 
920  if(Status==0) break;
921 
922  if(SlotId==1 && (ID==0 || ID==1)) CoreTraces[ID][j] = tmp16;
923  else if(SlotId==1) break;
924  else SegmentTraces[SegId][j] = tmp16;
925  }
926 
927  dbuffer += fTraceLengthRaw;
928  PosInBuff += fTraceLengthRaw;
929  }
930 
931  delete [] compBuffer;
932  dbuffer -= PosInBuff;
933  delete [] dbuffer;
934  }
935 
936 
937  if(ListOfTS.size() !=1 )
938  {
939  int NViews = 0;
940 
941  fBitFlipTS++;
942 
943  for(unsigned int itest=0 ; itest<ListOfTS.size() ; itest++)
944  {
945  std::pair < unsigned long long, unsigned short > a_pair = ListOfTS[itest];
946  if(a_pair.second>NViews)
947  {
948  NViews = a_pair.second;
949  timestamp = a_pair.first;
950  }
951  }
952  }
953 
956 
957  return 1;
958 }
959 
961 {
962  if(fKeyFilterBuffer->FreeSize()==0)
963  {
964  fBashColor->SetInfoOut();
965  std::cout<<"The last key of the key filter file has been read."<<std::endl;
966  fBashColor->ResetColor();
967  fLastKeyIsRead = true;
968  return;
969  }
970 
972 
974 
977 
978  // fBashColor->SetColor(BashColor::kRed);
979  // std::cout<<"timestamp = "<<fNextTS<<std::endl;
980  // std::cout<<"EventNumber = "<<fNextEvtNbr<<std::endl;
981  // std::cout<<AgataKeyFactory::theFactory()->GetMessage(fKeyToLink->GetMessage());
982  // fBashColor->ResetColor();
983 }
984 
986 {
987  fBashColor->SetInfoOut();
988 
989  std::cout<<"******** MezzAFP producer stats: ********"<<std::endl<<std::endl;
990 
991  std::cout<<"Crystal: "<<fCrystalName<<std::endl;
992 
993  std::cout<<"Number of imput events : "<<fNEvts<<std::endl;
994  std::cout<<"First TimeStamp seen : "<<FirstTimeStamp<<std::endl;
995  std::cout<<"Last TimeStamp seen : "<<LastTimeStamp<<std::endl;
996 
997  double TotalTimeInS = (LastTimeStamp-FirstTimeStamp)*10.*1e-9;
998 
999  int TH = (int)(TotalTimeInS/3600.);
1000  int TMin = (int)((TotalTimeInS/3600.-TH)*60.);
1001  int TSec = (int)(((TotalTimeInS/3600.-TH)*60.-TMin)*60.);
1002 
1003  std::cout<<"Elapsed time (s) : "<<TotalTimeInS<<" ( "<<TH<<"h"<<TMin<<"'"<<TSec<<"'' )"<<std::endl<<std::endl;
1004 
1005  if(fUseKeyFilter)
1006  {
1007  std::cout<<"Number of filtered events : "<<fNEvts-fNIgnoredEvts<<" ( "<<((float)(fNEvts-fNIgnoredEvts))/((float)fNEvts)*100.<<"\% )"<<std::endl;
1008  std::cout<<"Number of ignored events : "<<fNIgnoredEvts<<" ( "<<((float)fNIgnoredEvts)/((float)fNEvts)*100.<<"% )"<<std::endl;
1009  }
1010 
1011  fBashColor->SetErrorOut();
1012  if(fBitFlipMezzLength>0) std::cout<<"Number of MezzLength flipped bits : "<<fBitFlipMezzLength<<std::endl;
1013  if(fBitFlipTraceLength>0) std::cout<<"Number of TraceLength flipped bits : "<<fBitFlipTraceLength<<std::endl;
1014  if(fBitFlipSegId>0) std::cout<<"Number of SegId flipped bits : "<<fBitFlipSegId<<std::endl;
1015  if(fBitFlipTS>0) std::cout<<"Number of Timestamp flipped bits : "<<fBitFlipTS<<std::endl;
1016  fBashColor->SetInfoOut();
1017 
1018  std::cout<<std::endl<<"*******************************************"<<std::endl;
1019 
1020  fBashColor->ResetColor();
1021  return;
1022 }
1023 
1025 {
1026  fNEvts=0;
1027  fNIgnoredEvts=0;
1028 
1029  fBitFlipMezzLength = 0;
1030  fBitFlipTraceLength = 0;
1031  fBitFlipSegId = 0;
1032  fBitFlipTS = 0;
1033 
1034  FirstTimeStamp = 0;
1035  LastTimeStamp = 0;
1036 }
1037 
1038 std::string ReadMezzAFP::ConvertToBinary(unsigned long long n)
1039 {
1040  std::ostringstream *bin = new std::ostringstream();
1041 
1042  ProcessConvToBinary(n, bin);
1043 
1044  std::string binvalue = ((std::string)(*bin).str());
1045  delete bin;
1046 
1047  return binvalue;
1048 }
1049 
1050 void ReadMezzAFP::ProcessConvToBinary(unsigned long long n, std::ostringstream *str)
1051 {
1052  if (n / 2 != 0) {
1053  ProcessConvToBinary(n / 2, str);
1054  }
1055  (*str)<<(int)(n % 2);
1056 }
ADF::AgataKey * fKeyToLink
Definition: ReadMezzAFP.h:128
static const int kNCC
Definition: ReadMezzAFP.h:46
bool fUseKeyFilter
Definition: ReadMezzAFP.h:125
virtual Key * GetKey()=0
To get the Key associated to this frame.
virtual Frame * GetFrame() const
Definition: Frame.h:625
unsigned short * CoreTraces[kNCC]
Definition: ReadMezzAFP.h:95
virtual void SetStatus(UShort_t s)
Definition: CrystalFrame.h:61
virtual GeCore * GetCore(UShort_t)=0
to get each core
It defines the interface needed to be a narval actor (producer).
Base class for a Frame.
Definition: Frame.h:73
LogMessage & error(LogMessage &)
LogMessage & warning(LogMessage &)
bool fLastKeyIsRead
Definition: ReadMezzAFP.h:126
static const int mezzanineChanHeader
Definition: ReadMezzAFP.h:114
virtual GeSegment * GetSegment(UShort_t)=0
to get individual segment
virtual void process_initialise(unsigned int *error_code)
Constructor implementation.
virtual Signal * GetSignal()
Definition: CrystalFrame.h:56
static const int MIN_1x6
Definition: ReadMezzAFP.h:116
Interface to AgataKey.
float CoreE[kNCC]
Definition: ReadMezzAFP.h:101
unsigned short SegID[kNSG]
Definition: ReadMezzAFP.h:99
A Block of Frames.
Definition: FrameBlock.h:43
ADF::GeCore * coreMezz
Definition: ReadMezzAFP.h:106
void SetEoB(Bool_t b)
Definition: FrameBlock.h:89
unsigned int fTraceLengthRaw
Definition: ReadMezzAFP.h:92
LogMessage & nline(LogMessage &)
virtual ~ReadMezzAFP()
Definition: ReadMezzAFP.cpp:83
virtual void SetModeIO(ConfAgent::EMode mode)
Definition: FrameBlock.h:81
void SetModel(ConfAgent::EModel model)
Definition: FrameIO.cpp:93
Data produced fro a Crystal.
Definition: CrystalFrame.h:106
static const int kNSG
Definition: ReadMezzAFP.h:47
unsigned short crystal_status
Definition: ReadMezzAFP.h:86
Base class for a Global Object.
Definition: GObject.h:115
void Fired(Bool_t b=true)
Fired (default) or not this trigger.
Definition: Trigger.h:106
static void process_config(const char *, unsigned int *)
to init globals (static) from a directory
virtual ULong64_t GetTimeStamp() const =0
To set the timestamp.
UInt_t Offset() const
it returns the current position in the buffer
Definition: BufferIO.h:240
virtual void SetID(UShort_t id)
Definition: CrystalFrame.h:71
unsigned short CoreStatus[kNSG]
Definition: ReadMezzAFP.h:102
static UInt_t kDefaultLength
Definition: CrystalFrame.h:109
virtual Bool_t Register(DFTrigger *)
To register a trigger.
Definition: FrameIO.cpp:368
const UInt_t aMByte
Definition: BaseBuffer.h:36
bool NewFile()
Definition: ReadMezzAFP.cpp:94
header file for ReadMezzAFP.cpp
LogMessage & info(LogMessage &)
manipulator to modify the LogMessage
virtual UInt_t GetKeyLength() const
Unique number corresponding to a type of Key.
Definition: Key.h:210
unsigned int fNextEvtNbr
Definition: ReadMezzAFP.h:132
virtual UInt_t GetEventNumber() const =0
To get the event number encoded.
const std::string & GetConfPath()
To get the algo path associated with the current actor.
Base class for version numbers.
Definition: Version.h:38
ConfAgent.
Definition: ConfAgent.h:63
unsigned int evnumber
Definition: ReadMezzAFP.h:87
virtual SharedFP * SetOutputFrame(Frame *frame)
Once a trigger has fired, the result of the algorithm is set through this.
Definition: Trigger.h:512
header file for BufferIO.cpp
virtual void Detach(FrameBlock *in, FrameBlock *out)
Definition: FrameIO.cpp:741
UInt_t FreeSize() const
it returns the number of free bytes to the end
Definition: BufferIO.h:236
void SetStatus(EStatus stat)
Definition: FrameIO.h:110
virtual void SetProcessMethod(const char *)
To set the current method.
ADF::SharedFP * fFrameCrystal_Out
Definition: ReadMezzAFP.h:109
FILE * fKeyFilterFile
Definition: ReadMezzAFP.h:124
static const int mezzanineMezzHeader
Trigger for the input frame.
Definition: ReadMezzAFP.h:113
unsigned short crystal_id
Definition: ReadMezzAFP.h:85
virtual void SetE(Double_t e)
Definition: CrystalFrame.h:66
virtual void Set(UShort_t, UInt_t)=0
Method to set the value for a particular bin of the signal.
LogMessage & dolog(LogMessage &)
virtual UInt_t Write()
It writes to the Frame the content of the dedicated structures.
Definition: Frame.h:206
unsigned short * SegmentTraces[kNSG]
Definition: ReadMezzAFP.h:94
virtual void ClearMessage()
To clear the current message.
Bool_t LinkItem(const Char_t *, const Char_t *, void *)
Only for basic type ... otherwise better to use the most general Link method.
Definition: GObject.cpp:120
unsigned long long timestamp
Definition: ReadMezzAFP.h:88
void NextKeyToFind()
virtual UInt_t GetLength() const =0
total length for that frame
virtual Bool_t Record(DFTrigger *)
To record a frame trigger.
Definition: FrameIO.cpp:608
float SegE[kNSG]
Definition: ReadMezzAFP.h:97
virtual Bool_t Link(const Char_t *, UInt_t)
Link an external buffer to this key.
Definition: Key.cpp:74
virtual void Reset()=0
Reset the current frame.
ADF::BufferIO * fKeyFilterBuffer
Definition: ReadMezzAFP.h:130
void ResetStats()
ADF::LogMessage & endl(ADF::LogMessage &log)
virtual void SetFile(FILE *file, Long64_t max_size=kMaxUInt_t)
Definition: FrameBlock.h:405
unsigned short CoreID[kNSG]
Definition: ReadMezzAFP.h:103
virtual void process_reset(unsigned int *error_code)
Destructor implementation.
UInt_t Import(const Char_t *from, UInt_t size_ext_buf)
Import the given array in this buffer.
Definition: BufferIO.cpp:298
virtual Bool_t Reserve(UInt_t, Bool_t=false, UInt_t=0u)
Reserve the given size for writing.
Definition: FrameBlock.h:137
virtual void Print(std::ostream &out=std::cout) const
Print some informations (statistics)
Definition: FrameIO.cpp:571
virtual unsigned int ProcessBlock(ADF::FrameBlock &)
Produce one block of data.
const Int_t kMaxInt_t
Definition: ADFConfig.h:101
unsigned long long LastTimeStamp
Definition: ReadMezzAFP.h:90
virtual void Attach(FrameBlock *in, FrameBlock *out)
Attach a block to this. Rewind called if DoRewind set to true (Default)
Definition: FrameIO.cpp:724
unsigned short SegStatus[kNSG]
Definition: ReadMezzAFP.h:98
ADF::AgataFrameTrigger fTrigger
Definition: ReadMezzAFP.h:110
virtual std::string & GetProcessName()
To get the Process name.
unsigned long long FirstTimeStamp
Definition: ReadMezzAFP.h:89
virtual void SetT(Double_t t)
Definition: CrystalFrame.h:95
LogMessage Log
to send messages to the log server
const Int_t size
Definition: BenchIO.C:24
virtual void SetName(const char *name)
Definition: FrameIO.h:102
unsigned long long fNextTS
Definition: ReadMezzAFP.h:133
void PrintStats()
ADF::GeSegment * segMezz
Definition: ReadMezzAFP.h:105
Base class that described an item in a Factory.
Definition: FactoryItem.h:52
UInt_t SetOffset(UInt_t off=0u) const
change the current position.
Definition: BufferIO.cpp:122