/data3/calcul/jacquem/working_dir/Micromegas/micromegasFrameWork/src/reconstruction.cpp

Go to the documentation of this file.
00001 /* @version $Revision: 1945 $ * @modifiedby $Author: jacquem $ * @lastmodified $Date: 2012-11-20 10:37:04 +0100 (Tue, 20 Nov 2012) $ */
00002 
00003 #include "geometry/Chamber.hh"
00004 #include "geometry/Board.hh"
00005 #include "geometry/Chip.hh"
00006 #include "geometry/Channel.hh"
00007 #include "geometry/Dif.hh"
00008 #include "geometry/Detector.hh"
00009 
00010 #include "event/Run.hh"
00011 #include "event/Event.hh"
00012 
00013 #include "parser/AcquisitionParser.hh"
00014 #include "parser/Centaure.hh"
00015 #include "parser/Hardroc1Reader.hh"
00016 #include "parser/Hardroc2XdaqReader.hh"
00017 #include "parser/Hardroc2LabviewReader.hh"
00018 #include "parser/MicrorocOldLabviewReader.hh"
00019 #include "parser/MicrorocLabviewReader.hh"
00020 #include "parser/MicrorocXDaqReader.hh"
00021 #include "parser/DifSynchroReader.hh"
00022 #include "parser/DiracReader.hh"
00023 #include "parser/DiracLabview.hh"
00024 #include "parser/CalibHR1Parser.hh"
00025 #include "parser/CalibHR2Parser.hh"
00026 #include "parser/CalibMicrorocParser.hh"
00027 #include "parser/TestMicrorocParser.hh"
00028 
00029 #include "xml/XMLTool.hh"
00030 
00031 #include "tools/Log.hh"
00032 #include "tools/MicroException.hh"
00033 #include "tools/Arguments.hh"
00034 
00035 #include "MTEvent.hh"
00036 #include "MTRun.hh"
00037 #include "slowControl/SlowControlManager.hh"
00038 #include "slowControl/SlowControlEntry.hh"
00039 
00040 #include "mysql/Mysql.hh"
00041 
00042 #include <iostream>
00043 #include <iomanip>
00044 #include <sstream>
00045 #include <iostream>
00046 
00047 #include <stdlib.h>
00048 
00049 
00050 #include "TFile.h"
00051 #include "TTree.h"
00052 
00053 
00054 
00055 #include "IO/LCWriter.h"
00056 #include "IMPL/LCRunHeaderImpl.h"
00057 #include "IMPL/LCEventImpl.h"
00058 #include "IMPL/LCTOOLS.h"
00059 
00060 #include "lcio/MLcio.hh"
00061 
00062 using namespace lcio;
00063 using namespace std;
00064 
00065 int main(int argc, char **argv)
00066 {
00067   string steerName;
00068 
00069 
00070   // set verbose level
00071   FILELog::ReportingLevel() = FILELog::FromString(INFO);
00072 
00073   ui32 slowcontrolNotFound = 0;
00074   ui32 eventNotValid = 0;
00075 
00076 //----- Control usage and option
00077   Arguments arg(argc,argv,"reconstruction steerfile.xml type(root|lcio) [-r runId]  [-l nbEvent] -dif[id1,id2,...] [-sql 1]  [-forceanalog 1] [-q 1] [-batch 1] [-skip nbEvent]  [-v(ERROR || WARNING ||  INFO  || DEBUG || DEBUG1)]");
00078   
00079   if ( arg.getNbOfArgs() != 2) { //  steerfile.xml type
00080     arg.usage();
00081     exit(1);
00082   }
00083   // Get command parameter : here steering file
00084   steerName.assign(arg.getArgument(1));
00085   
00086   string outputType = arg.getArgument(2);
00087 
00088   bool outputLcio = true;
00089   if ( outputType.compare("root") == 0 )
00090   {   
00091     outputLcio = false;
00092   }
00093   
00094   
00095   bool batch = false;
00096   if ( arg.getOption("-batch").size() != 0 )
00097   {
00098     if ( atoi(arg.getOption("-batch").c_str()) == 1) 
00099     {
00100       cout << "Batch mode" << endl;
00101       batch = true;
00102     }
00103   }
00104 
00105   if ( arg.getOption("-v").size() != 0 )
00106   {
00107     cout << "VERBOSE LEVEL: " << arg.getOption("-v") << endl;
00108     FILELog::ReportingLevel() = FILELog::FromString(arg.getOption("-v"));
00109   }
00110 
00111   bool sql = false;
00112   if ( arg.getOption("-sql").size() != 0 )
00113   {
00114     cout << "Mysql database will be updated" << endl;
00115     sql = true;
00116   }
00117 
00118   ui32 limitEvent = 0;
00119   string sLimitEvent;
00120   bool limit = false;
00121   if ( arg.getOption("-l").size() != 0 ) 
00122   {
00123     limitEvent = atoi(arg.getOption("-l").c_str());
00124     sLimitEvent = arg.getOption("-l");
00125     limit = true;
00126     FILE_LOG(logINFO)  <<"Number of reconstruct event is limited to " << limitEvent << endl;
00127   } 
00128 
00129   ui32 skipEvent = 0;
00130   //string sSkipEvent;
00131   bool skip = false;
00132   if ( arg.getOption("-skip").size() != 0 ) 
00133   {
00134     skipEvent = atoi(arg.getOption("-skip").c_str());
00135     skip = true;
00136     FILE_LOG(logINFO)  <<"Skip " << skipEvent << " events." << endl;
00137   } 
00138 
00139   set<unsigned int>*difList = NULL;
00140   if ( arg.getOption("-dif").size() != 0 )
00141   {
00142     difList = new set<unsigned int>();
00143     string sdifList = arg.getOption("-dif");
00144     string difId;
00145     stringstream stream(sdifList);
00146     cout  <<"Create hit only for following dif: " ;
00147     while( getline(stream, difId, ',') )
00148     {
00149       difList->insert(atoi(difId.c_str()));
00150       cout << atoi(difId.c_str()) << ", ";
00151     }
00152     cout << endl;
00153   }
00154 
00155   // Add by Renaud to limit warnings during microroc qualifaction (no database is used)
00156   bool is_qualification = false;
00157   if ( arg.getOption("-q").size() != 0 ) 
00158   {
00159         is_qualification = true;
00160   }
00161   
00162   /* alow to create analog hits event if no digital hit correspond. Warning hit will have no bcid information
00163                              // http://lappwiki01.in2p3.fr/Linear_Collider_LAPP/index.php/MicromegasFramework#Reconstruction_de_la_lecture_analogique_avec_les_Microroc
00164   */
00165   bool forceAnalog = false;
00166   if ( arg.getOption("-forceanalog").size() != 0 ) 
00167   {
00168         forceAnalog = true;
00169   }
00170 
00171   string svnVersion = "0";
00172   // test if steer file exist
00173   FILE *file = fopen(steerName.c_str(), "r");
00174   if(file == NULL){
00175     FILE_LOG(logERROR) << "Steer file ["<< steerName.c_str() << "] does not exist" << endl;
00176     exit(1);
00177     fclose(file);
00178   }
00179   else
00180   {
00181     // create Run, set detector and steerDesc from steer XML file
00182     SteerDesc steerDesc;
00183     XMLTool xml;
00184     xml.parse(steerDesc, steerName); // parse steer file and fill steerDesc
00185 
00186     fclose(file);
00187 
00188     string slowControlPath = steerDesc.getSlowControlPath();
00189     SlowControlManager sc;
00190     sc.build(steerDesc);
00191     sc.readDB(slowControlPath);
00192 
00193     FILE_LOG(logINFO) <<  "slowControl entries:[" << sc.getNbEntries() << "]" << endl;
00194 
00195     TFile *hfile = NULL;
00196     MTEvent *rootEvt = NULL;
00197 
00198     LCWriter* lcWrt = NULL;
00199     LCRunHeaderImpl* runHdr = NULL ;
00200 
00201     if ( outputLcio )
00202     {
00203       runHdr = new LCRunHeaderImpl() ;
00204 
00205       string detName("micromegas_m2")  ;
00206       runHdr->setDetectorName( detName ) ;
00207 
00208       string ecalName("m2") ;
00209       runHdr->addActiveSubdetector( ecalName ) ;
00210 
00211       string telName("telecsope") ;
00212       runHdr->addActiveSubdetector( telName ) ;
00213       // add some parameters to the run header
00214       runHdr->parameters().setValue( "cerate lcio for micromegas" , "lcioTest.cc" ) ;
00215       IntVec iv(3) ;
00216       iv[0] = 1 ;
00217       iv[1] = 2 ;
00218       iv[2] = 3 ;
00219       runHdr->parameters().setValues( "SomeIndices" , iv ) ;
00220       runHdr->parameters().setValues( "SomeOtherIndices" , iv ) ;
00221     }
00222     else 
00223     {
00224       string rootFile = "default.root";
00225       if ( steerDesc.outputFile.length() != 0)  { rootFile = steerDesc.outputFile; }
00226       hfile = new TFile(rootFile.data(),"RECREATE","Micromegas LAPP");
00227 
00228       // Start ROOT tree filling
00229       rootEvt = new MTEvent();   // MTEvent is a Root base class which can be write to a ROOT File.
00230     }
00231     unsigned int totalNbEvents = 0;
00232     unsigned int totalNbHits = 0;
00233     unsigned int totalNbEventPerRawFile = 0;
00234     UInt_t lastEventId = 0;
00235     // reconstruct event from input data files
00236     FILE_LOG(logINFO) << "Start reconstruction for " << steerName  << endl;
00237     FILE_LOG(logINFO) << "Output file " << steerDesc.outputFile  <<  endl;
00238     FILE_LOG(logINFO) <<  "Output format " << outputType << "." << endl;
00239 
00240     Detector detector;
00241     if ( ! detector.build(steerDesc) == steerDesc.chambers.size() )
00242     {
00243       FILE_LOG(logERROR) << "Geometry Error. Please check your XML file."  << endl;
00244       exit(-1);
00245     }
00246     Run run(detector);
00247     svnVersion = run.getSvnrev();
00248     if ( ! steerDesc.setRun(run)) // Set detector with xml file content
00249     { exit(1); }
00250 
00251     // create the proper parser depending on file type
00252     const std::vector<input_info_t>* inputFiles = &(steerDesc.inputFiles);
00253 
00254     ui16 nbFile =  inputFiles->size();
00255     for (int fileIndex = 0; fileIndex < nbFile; fileIndex++)
00256     {
00257       const input_info_t &inputInfo = inputFiles->at(fileIndex);
00258       std::string currentType = inputInfo.type;
00259       FILE *inputFile = fopen(inputInfo.path.data(),"rb");
00260       if ( inputFile == NULL)
00261       {
00262         FILE_LOG(logERROR) << "Could not open " << inputInfo.path << endl;
00263         exit(1);
00264         continue;
00265       }
00266 
00267 
00268       FILE_LOG(logINFO) << "Open acquisition file: " << inputInfo.path << " of type:" << currentType << endl;
00269       AcquisitionParser *parser;
00270 
00271       if (currentType == Centaure::type())
00272       {
00273         parser = new Centaure(run, inputFile, lastEventId);
00274       }
00275       else if (currentType == Hardroc1Reader::type())
00276       {
00277         parser = new Hardroc1Reader(run, inputFile, lastEventId);
00278       }
00279       else if (currentType == Hardroc2XdaqReader::type())
00280       {
00281         parser = new Hardroc2XdaqReader(run, inputFile, lastEventId);
00282       }
00283       else if (currentType == Hardroc2LabviewReader::type())
00284       {
00285         parser = new Hardroc2LabviewReader(run, inputFile, lastEventId);
00286       }
00287       else if (currentType == CalibHR1Parser::type())
00288       {
00289         parser = new CalibHR1Parser(run, inputFile, lastEventId);
00290       }
00291       else if (currentType == CalibHR2Parser::type())
00292       {
00293         parser = new CalibHR2Parser(run, inputFile, lastEventId);
00294       }
00295       else if (currentType == MicrorocOldLabviewReader::type())
00296       {
00297         parser = new MicrorocOldLabviewReader(run, inputFile, lastEventId);
00298       }
00299       else if (currentType == CalibMicrorocParser::type())
00300       {
00301         parser = new CalibMicrorocParser(run, inputFile, lastEventId);
00302       }
00303       else if (currentType == TestMicrorocParser::type())
00304       {
00305         parser = new TestMicrorocParser(run, inputFile, lastEventId);
00306       }
00307       else if (currentType == DiracReader::type())
00308       {
00309         parser = new DiracReader(run, inputFile, lastEventId);
00310       }
00311       else if (currentType == DiracLabview::type())
00312       {
00313         parser = new DiracLabview(run, inputFile, lastEventId);
00314       }
00315       else if (currentType == DifSynchroReader::type())
00316       {
00317         parser = new DifSynchroReader(run, inputFile, lastEventId);
00318       }
00319       else if (currentType == MicrorocLabviewReader::type())
00320       {
00321         parser = new MicrorocLabviewReader(run, inputFile, lastEventId,forceAnalog, difList);
00322         if ( skip)  { parser->setSkipEvent(skipEvent) ; } 
00323       }
00324       else if (currentType == MicrorocXDaqReader::type())
00325       {
00326         parser = new MicrorocXDaqReader(run, inputInfo.path.data(), lastEventId,forceAnalog, difList);
00327         if ( skip)  { parser->setSkipEvent(skipEvent) ; } 
00328       }
00329       else if (currentType == "xdaqHR2")
00330       {
00331         parser = new MicrorocXDaqReader(run, inputInfo.path.data(), lastEventId,difList);
00332       }
00333 
00334       else
00335       { // type non pris en charge
00336       FILE_LOG(logERROR) << "NOT SUPPORTED ---- type:" << currentType << endl;
00337       fclose(inputFile);
00338       continue;
00339       }
00340 
00341       totalNbEventPerRawFile = 0;
00342 
00343       unsigned int configNum = 1;
00344       Event *event = new Event(run);
00345 
00346       ui16 parserResult = parser->getNextEvent(*event);
00347       while (parserResult == NEW_CONFIG)
00348       {  
00349         size_t  found=inputInfo.path.find_last_of("/\\");
00350         string name = inputInfo.path.substr(found+1);
00351         string s = "chaine";
00352         stringstream buffer;
00353         buffer << name << "_" << configNum ;
00354 
00355 
00356         TTree mt(buffer.str().c_str(),"MicroMegas event");
00357 
00358         if (  outputLcio )
00359         {
00360         // create sio writer
00361         cout << " runHdr->setRunNumber[" << inputInfo.runId << "]" << endl;
00362         runHdr->setRunNumber(inputInfo.runId ) ;
00363         lcWrt = LCFactory::getInstance()->createLCWriter()  ;
00364         string lcioFile = buffer.str();
00365         lcWrt->open( lcioFile , LCIO::WRITE_NEW )  ;
00366         }
00367         else
00368         {
00369         //              FILE_LOG(logINFO) << "Create new TTRee:["<< buffer.str() << "]" << endl;
00370         mt.SetMaxTreeSize(40000000000); // 40 GB
00371         mt.Branch("MTEvent",&rootEvt,16000,2);// second argument is class of evt!!!
00372         }
00373 
00374         // now parse the whole file
00375         // now fill the run structure
00376         // mtRun = run;
00377         configNum++;
00378 
00379         parserResult = parser->getNextEvent(*event);
00380 
00381         run.setRawDataFilename(inputInfo.path);
00382 //        MTRun mtRun(run);
00383 
00384         while (parserResult == EVENT_CORRECT || parserResult == EVENT_ERROR  ) // && ( !limit || totalNbEventPerRawFile < limitEvent  ))
00385         {
00386           if ( parserResult == EVENT_CORRECT )
00387           {
00388             try
00389             {
00390               if ( sc.getNbEntries() > 0 )
00391               {
00392               const double evTimeStamp = event->getTimeStamp();
00393                 try
00394                 {
00395                   const SlowControlEntry* slowcontrolEntry = sc.getEntry(evTimeStamp);
00396                   event->setSlowControlParam(slowcontrolEntry);
00397                 }
00398                 catch ( MicroException e)
00399                 {
00400                   FILE_LOG(logWARNING) << e.getMessage() << endl;
00401                   slowcontrolNotFound++;
00402                 }
00403               }
00404               if ( ! outputLcio )
00405               {
00406                 *rootEvt=*event;   // ! surcharge operator=
00407               }
00408               totalNbHits =  totalNbHits + event->getChannelHitSize();
00409 
00410               if ( event->getId() % 1== 0)
00411               {
00412                 if ( batch )
00413                 {
00414                   FILE_LOG(logINFO  ) << "Write Event[" << event->getId() << "] total number of reconstruted event' hits[" << event->getChannelHitSize() << "] valid[" << event->getValidFlag() << "]" << endl;
00415                 }
00416                 else
00417                 {  
00418                   if ( ! event->isValid()  ) 
00419                   {
00420                     FILE_LOG(logINFO  ) << "Write Event[" << event->getId()-1 << "] total number of reconstruted event' hits[" << event->getChannelHitSize() << "] , FLAG[" << hex  << event->getValidFlag() <<  "] ->["  << event->getValidFlagString() << "]" << dec <<endl;
00421                   }
00422                   else
00423                   {
00424                     FILE_LOG(logINFO  ) << "Write Event[" << event->getId()-1 << "] total number of reconstruted event' hits[" << event->getChannelHitSize()  << "\t\t\t\t   \r" << flush;
00425                   }
00426                 }
00427                 //if ( event->getValidFlag() != VALID ) { eventNotValid++; }
00428                 if ( ! event->isValid()) { eventNotValid++; }
00429                 
00430               }
00431 
00432               lastEventId = event->getId();
00433 
00434               if (  outputLcio )
00435               {
00436                 // write the event to the file
00437                 LCEventImpl* lcioEvtImpl =  new LCEventImpl();
00438                 MLcio::setLCEventImp(*lcioEvtImpl,*event);
00439                 lcWrt->writeEvent( lcioEvtImpl ) ;
00440                 // dump the event to the screen
00441                 //LCTOOLS::dumpEvent( lcioEvtImpl ) ;
00442                 // ------------ IMPORTANT ------------- !
00443                 // we created the event so we need to delete it ...
00444                 delete lcioEvtImpl ;
00445               }
00446 
00447               else 
00448               {
00449                 mt.Fill(); // Fill the TTree
00450                 rootEvt->Clear(); // free memory
00451               }
00452               totalNbEvents++;
00453               totalNbEventPerRawFile++;
00454 
00455             }
00456             catch (MicroException e) { FILE_LOG(logWARNING) << e.getMessage() << endl; }
00457             // Save all objects in this file
00458             delete event;
00459           } // END  if ( parserResult == EVENT_CORRECT)
00460           if ( !limit || totalNbEventPerRawFile < limitEvent  )
00461           {
00462             event = new Event(run);
00463             parserResult = parser->getNextEvent(*event);
00464           }
00465           else
00466           {
00467             parserResult = LAST_FILE_EVENT;
00468           }
00469         } // end for Events
00470         MTRun mtRun(run);
00471 
00472         if (  outputLcio )
00473         {
00474           lcWrt->close() ;
00475           delete lcWrt;
00476         }
00477         else if ( sql )
00478         {
00479           // get Run fronm database
00480           Mysql mysql;
00481           const input_info_t &inputInfo = inputFiles->at(0);
00482           string full = inputInfo.path.data();
00483           size_t last_slash = full.find_last_of("/")  +1 ;
00484           string name = full.substr(last_slash);
00485           string path = full.substr(0,last_slash-1);
00486           ui32 runId = mysql.getRunIdFromRawFile(path,name);
00487           if ( runId != UNDEFINED_ID )
00488           { 
00489             mtRun.SetRunId(runId);
00490             FILE_LOG(logINFO) << "Set Run Id from database[" << runId << "]"  << endl;
00491           }
00492         }
00493         mt.GetUserInfo()->Add(&mtRun);  // store run information in a TLIst a mt TTree
00494         TFile *curFile =mt.GetCurrentFile() ;
00495         curFile->Write("", TObject::kOverwrite);
00496 
00497         run.setDataFormat(0);
00498       }
00499 
00500       // free the memory and close the file
00501       delete parser;
00502       fclose(inputFile);
00503       FILE_LOG(logINFO) << endl << "-- " << inputInfo.path.data() <<
00504                         " Number of reconstructed Events:[" << totalNbEventPerRawFile << "]" << endl <<  endl;
00505     } // end for file index
00506 
00507 
00508 
00509     FILE_LOG(logINFO) << endl << "----- Total number of reconstructed Events:[" << totalNbEvents << "]" << endl;
00510     FILE_LOG(logINFO) << endl << "----- Total number of Hits:[" << totalNbHits << "]" << endl;
00511 
00512     if ( sql)
00513     {
00514       Mysql mysql;
00515       // Add reconstruction software in  DB if not already exist
00516       FILE_LOG(logINFO) << " mysql.add reconstruction software to DB (" << svnVersion << "]"  << endl;
00517       int softId = mysql.addReconstructionSoftware(svnVersion);
00518 
00519       // Add reconstruct file
00520       string fullName = steerDesc.outputFile ;
00521       size_t last_slash = fullName.find_last_of("/")  +1 ;
00522       string name = fullName.substr(last_slash);
00523       string path = fullName.substr(0,last_slash);
00524       string comment = "No comment.";
00525       if ( limitEvent != 0 ) { comment = "Reconstrcuted event limited to " + sLimitEvent + "." ; }
00526       i16 rebuildId = mysql.addRebuildFile(softId,path, name, true, totalNbEvents , totalNbHits, true, comment );
00527 
00528       // Get Raw file database Id if they are already existing
00529       for (int fileIndex = 0; fileIndex < inputFiles->size(); fileIndex++)
00530       {
00531         const input_info_t &inputInfo = inputFiles->at(fileIndex);
00532         string full = inputInfo.path.data();
00533         size_t last_slash = full.find_last_of("/")  +1 ;
00534         string name = full.substr(last_slash);
00535         string path = full.substr(0,last_slash-1);
00536         try 
00537         { 
00538           ui32 rawId = mysql.getRawFileId(path,name);
00539           mysql.connectRebuildAndRawFile(rawId,rebuildId);
00540         }
00541         catch ( MicroException e ) 
00542         {
00543           if (is_qualification == false)
00544           FILE_LOG(logWARNING) << "Raw file[" << path + name << "] not registerd in database." << endl;
00545         }
00546       }
00547     }
00548     /*
00549     The default value for AutoSave is to save a copy of the Tree header
00550     as soon as you have written 100 Mbytes (uncompressed) to the file.
00551     When AutoSave is called, a new key is created with the current header.
00552     If the creation of the key is successful, the previous key is deleted.
00553     At the end of the job, when you do tree.Write, a new key is
00554     always created, keeping the previous cycle of the same key, if any.
00555     You can use the option kOverwrite when calling the final tree.Write
00556     if you want to keep one single key.
00557     */
00558     if ( ! outputLcio )
00559     {
00560       hfile->Close();
00561     }
00562     FILE_LOG(logINFO) << "Number of slowcontrol data not found:" << slowcontrolNotFound << endl;
00563     FILE_LOG(logINFO) << "Number of non valid event: " << eventNotValid  << endl;
00564   }
00565   
00566   return 0;
00567 }
00568 

Generated on Mon Jan 7 13:15:22 2013 for MicromegasFramework by  doxygen 1.4.7