]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - STEER/STEER/AliSimulation.cxx
Technical fix in the CheckRecoCDBvsSimuCDB
[u/mrichter/AliRoot.git] / STEER / STEER / AliSimulation.cxx
index 6306067d5c144133595faa9377af8e5f6c46d2f3..2fbf9872af78085c2f06514dc4538b6b37916fc4 100644 (file)
@@ -13,7 +13,7 @@
  * provided "as is" without express or implied warranty.                  *
  **************************************************************************/
 
-/* $Id$ */
+/* $Id: AliSimulation.cxx 64623 2013-10-21 13:38:58Z rgrosso $ */
 
 ///////////////////////////////////////////////////////////////////////////////
 //                                                                           //
 //                                                                           //
 ///////////////////////////////////////////////////////////////////////////////
 
-#include <TCint.h>
 #include <TFile.h>
 #include <TGeoGlobalMagField.h>
 #include <TGeoManager.h>
 #include <TVirtualMC.h>
 #include <TVirtualMCApplication.h>
 #include <TDatime.h>
+#include <TInterpreter.h>
 
 #include "AliAlignObj.h"
 #include "AliCDBEntry.h"
 #include "AliRawReaderFile.h"
 #include "AliRawReaderRoot.h"
 #include "AliRun.h"
-#include "AliRunDigitizer.h"
+#include "AliDigitizationInput.h"
 #include "AliRunLoader.h"
+#include "AliStack.h"
 #include "AliSimulation.h"
 #include "AliSysInfo.h"
 #include "AliVertexGenFile.h"
 
+using std::ofstream;
 ClassImp(AliSimulation)
 
 AliSimulation *AliSimulation::fgInstance = 0;
-const char* AliSimulation::fgkDetectorName[AliSimulation::fgkNDetectors] = {"ITS", "TPC", "TRD", "TOF", "PHOS", "HMPID", "EMCAL", "MUON", "FMD", "ZDC", "PMD", "T0", "VZERO", "ACORDE", "HLT"};
+ const char* AliSimulation::fgkDetectorName[AliSimulation::fgkNDetectors] = {"ITS", "TPC", "TRD", 
+ "TOF", "PHOS", "HMPID", "EMCAL", "MUON", "FMD", "ZDC", "PMD", "T0", "VZERO", "ACORDE","AD",
+ "FIT","MFT","HLT"};
 
 //_____________________________________________________________________________
 AliSimulation::AliSimulation(const char* configFileName,
                             const char* name, const char* title) :
   TNamed(name, title),
 
+  fRunGeneratorOnly(kFALSE),
   fRunGeneration(kTRUE),
   fRunSimulation(kTRUE),
   fLoadAlignFromCDB(kTRUE),
@@ -174,6 +179,7 @@ AliSimulation::AliSimulation(const char* configFileName,
   fDeleteIntermediateFiles(kFALSE),
   fWriteSelRawData(kFALSE),
   fStopOnError(kFALSE),
+  fUseMonitoring(kFALSE),
   fNEvents(1),
   fConfigFileName(configFileName),
   fGAliceFileName("galice.root"),
@@ -196,6 +202,9 @@ AliSimulation::AliSimulation(const char* configFileName,
   fUseVertexFromCDB(0),
   fUseMagFieldFromGRP(0),
   fGRPWriteLocation(Form("local://%s", gSystem->pwd())),
+  fUseTimeStampFromCDB(0),
+  fTimeStart(0),
+  fTimeEnd(0),
   fQADetectors("ALL"),                  
   fQATasks("ALL"),     
   fRunQA(kTRUE), 
@@ -367,7 +376,7 @@ void AliSimulation::SetCDBLock() {
   // Set CDB lock: from now on it is forbidden to reset the run number
   // or the default storage or to activate any further storage!
   
-  ULong_t key = AliCDBManager::Instance()->SetLock(1);
+  ULong64_t key = AliCDBManager::Instance()->SetLock(1);
   if (key) fKey = key;
 }
 
@@ -620,6 +629,17 @@ Bool_t AliSimulation::Run(Int_t nEvents)
    
   if (nEvents > 0) fNEvents = nEvents;
 
+  // Run generator-only code on demand
+  if (fRunGeneratorOnly)
+  {
+    if(!RunGeneratorOnly())
+    {
+      if (fStopOnError) return kFALSE;
+    }
+    else
+      return kTRUE;
+  }
+
   // create and setup the HLT instance
   if (!fRunHLT.IsNull() && !CreateHLT()) {
     if (fStopOnError) return kFALSE;
@@ -712,7 +732,7 @@ Bool_t AliSimulation::Run(Int_t nEvents)
   
   
   // digits -> trigger
-  if (!RunTrigger(fTriggerConfig,fMakeDigits)) {
+  if (!fTriggerConfig.IsNull() && !RunTrigger(fTriggerConfig,fMakeDigits)) {
     if (fStopOnError) return kFALSE;
   }
 
@@ -740,15 +760,26 @@ Bool_t AliSimulation::Run(Int_t nEvents)
   AliSysInfo::AddStamp("RunHLT");
   
   //QA
-       if (fRunQA) {
-               Bool_t rv = RunQA() ; 
-               if (!rv)
-                       if (fStopOnError) 
-                               return kFALSE ;         
-       }
+  if (fRunQA) {
+      Bool_t rv = RunQA() ; 
+      if (!rv)
+         if (fStopOnError) 
+             return kFALSE ;
+  }
 
   AliSysInfo::AddStamp("RunQA");
 
+  TString snapshotFileOut("");
+  if(TString(gSystem->Getenv("OCDB_SNAPSHOT_CREATE")) == TString("kTRUE")){ 
+      AliInfo(" ******** Creating the snapshot! *********");
+      TString snapshotFile(gSystem->Getenv("OCDB_SNAPSHOT_FILENAME")); 
+      if(!(snapshotFile.IsNull() || snapshotFile.IsWhitespace())) 
+         snapshotFileOut = snapshotFile;
+      else 
+         snapshotFileOut="OCDB.root"; 
+      AliCDBManager::Instance()->DumpToSnapshotFile(snapshotFileOut.Data(),kFALSE); 
+  }
+
   // Cleanup of CDB manager: cache and active storages!
   AliCDBManager::Instance()->ClearCache();
 
@@ -969,6 +1000,7 @@ Bool_t AliSimulation::RunSimulation(Int_t nEvents)
   InitCDB();
   AliSysInfo::AddStamp("RunSimulation_InitCDB");
   InitRunNumber();
+
   SetCDBLock();
   AliSysInfo::AddStamp("RunSimulation_SetCDBLock");
   
@@ -980,6 +1012,9 @@ Bool_t AliSimulation::RunSimulation(Int_t nEvents)
     AliError("gAlice was already run. Restart aliroot and try again.");
     return kFALSE;
   }
+  
+  // Setup monitoring if requested
+  gAlice->GetMCApp()->SetUseMonitoring(fUseMonitoring);
 
   AliInfo(Form("initializing gAlice with config file %s",
           fConfigFileName.Data()));
@@ -1000,8 +1035,12 @@ Bool_t AliSimulation::RunSimulation(Int_t nEvents)
   }
 //
 // Execute Config.C
+  TInterpreter::EErrorCode interpreterError=TInterpreter::kNoError;
   gROOT->LoadMacro(fConfigFileName.Data());
-  gInterpreter->ProcessLine(gAlice->GetConfigFunction());
+  Long_t interpreterResult=gInterpreter->ProcessLine(gAlice->GetConfigFunction(), &interpreterError);
+  if (interpreterResult!=0 || interpreterError!=TInterpreter::kNoError) {
+    AliFatal(Form("execution of config file \"%s\" failed with error %d", fConfigFileName.Data(), (int)interpreterError));
+  }
   AliSysInfo::AddStamp("RunSimulation_Config");
 
 //
@@ -1032,6 +1071,23 @@ Bool_t AliSimulation::RunSimulation(Int_t nEvents)
          }
       }
   }
+
+  // If requested we take the SOR and EOR time-stamps from the GRP and use them
+  // in order to generate the event time-stamps
+  if (fUseTimeStampFromCDB) {
+    AliGRPManager grpM;
+    grpM.ReadGRPEntry();
+    const AliGRPObject *grpObj = grpM.GetGRPData();
+    if (!grpObj || (grpObj->GetTimeEnd() <= grpObj->GetTimeStart())) {
+      AliError("Missing GRP or bad SOR/EOR time-stamps! Switching off the time-stamp generation from GRP!");
+      fTimeStart = fTimeEnd = 0;
+      fUseTimeStampFromCDB = kFALSE;
+    }
+    else {
+      fTimeStart = grpObj->GetTimeStart();
+      fTimeEnd = grpObj->GetTimeEnd();
+    }
+  }
   
   if(AliCDBManager::Instance()->GetRun() >= 0) { 
     AliRunLoader::Instance()->SetRunNumber(AliCDBManager::Instance()->GetRun());
@@ -1047,7 +1103,6 @@ Bool_t AliSimulation::RunSimulation(Int_t nEvents)
 
    gMC->SetMagField(TGeoGlobalMagField::Instance()->GetField());
    AliSysInfo::AddStamp("RunSimulation_GetField");
-   
    gAlice->GetMCApp()->Init();
    AliSysInfo::AddStamp("RunSimulation_InitMCApp");
 
@@ -1167,7 +1222,6 @@ Bool_t AliSimulation::RunSimulation(Int_t nEvents)
 
   // Create the Root Tree with one branch per detector
   //Hits moved to begin event -> now we are crating separate tree for each event
-
   gMC->ProcessRun(nEvents);
 
   // End of this run, close files
@@ -1179,6 +1233,75 @@ Bool_t AliSimulation::RunSimulation(Int_t nEvents)
   return kTRUE;
 }
 
+//_____________________________________________________________________________
+Bool_t AliSimulation::RunGeneratorOnly()
+{
+  // Execute Config.C
+  TInterpreter::EErrorCode interpreterError=TInterpreter::kNoError;
+  gROOT->LoadMacro(fConfigFileName.Data());
+  Long_t interpreterResult=gInterpreter->ProcessLine(gAlice->GetConfigFunction(), &interpreterError);
+  if (interpreterResult!=0 || interpreterError!=TInterpreter::kNoError) {
+    AliFatal(Form("execution of config file \"%s\" failed with error %d", fConfigFileName.Data(), (int)interpreterError));
+  }
+
+  // Setup the runloader and generator, check if everything is OK
+  AliRunLoader* runLoader = AliRunLoader::Instance();
+  AliGenerator* generator = gAlice->GetMCApp()->Generator();
+  if (!runLoader) {
+    AliError(Form("gAlice has no run loader object. "
+                  "Check your config file: %s", fConfigFileName.Data()));
+    return kFALSE;
+  }
+  if (!generator) {
+    AliError(Form("gAlice has no generator object. "
+                  "Check your config file: %s", fConfigFileName.Data()));
+    return kFALSE;
+  }
+
+  runLoader->LoadKinematics("RECREATE");
+  runLoader->MakeTree("E");
+
+  // Create stack and header
+  runLoader->MakeStack();
+  AliStack*  stack      = runLoader->Stack();
+  AliHeader* header     = runLoader->GetHeader();
+
+  // Intialize generator
+  generator->Init();
+  generator->SetStack(stack);
+
+  // Run main generator loop
+
+  for (Int_t iev=0; iev<fNEvents; iev++)
+  {
+    // Initialize event
+    header->Reset(0,iev);
+    runLoader->SetEventNumber(iev);
+    stack->Reset();
+    runLoader->MakeTree("K");
+
+    // Generate event
+    generator->Generate();
+
+    // Finish event
+    header->SetNprimary(stack->GetNprimary());
+    header->SetNtrack(stack->GetNtrack());
+    stack->FinishEvent();
+    header->SetStack(stack);
+    runLoader->TreeE()->Fill();
+    runLoader->WriteKinematics("OVERWRITE");
+  }
+
+  // Finalize
+  generator->FinishRun();
+  // Write file
+  runLoader->WriteHeader("OVERWRITE");
+  generator->Write();
+  runLoader->Write();
+
+  return kTRUE;
+}
+
 //_____________________________________________________________________________
 Bool_t AliSimulation::RunSDigitization(const char* detectors)
 {
@@ -1240,50 +1363,56 @@ Bool_t AliSimulation::RunDigitization(const char* detectors,
   Int_t nStreams = 1;
   if (fBkgrdFileNames) nStreams = fBkgrdFileNames->GetEntriesFast() + 1;
   Int_t signalPerBkgrd = GetNSignalPerBkgrd();
-  AliRunDigitizer* manager = new AliRunDigitizer(nStreams, signalPerBkgrd);
-  // manager->SetEmbeddingFlag(fEmbeddingFlag);
-  manager->SetInputStream(0, fGAliceFileName.Data());
+  AliDigitizationInput digInp(nStreams, signalPerBkgrd);
+  // digInp.SetEmbeddingFlag(fEmbeddingFlag);
+  digInp.SetRegionOfInterest(fRegionOfInterest);
+  digInp.SetInputStream(0, fGAliceFileName.Data());
   for (Int_t iStream = 1; iStream < nStreams; iStream++) {
-    const char* fileName = ((TObjString*)
-                           (fBkgrdFileNames->At(iStream-1)))->GetName();
-    manager->SetInputStream(iStream, fileName);
+    const char* fileName = ((TObjString*)(fBkgrdFileNames->At(iStream-1)))->GetName();
+    digInp.SetInputStream(iStream, fileName);
   }
-
+  TObjArray detArr;
+  detArr.SetOwner(kTRUE);
   TString detStr = detectors;
   TString detExcl = excludeDetectors;
-  manager->GetInputStream(0)->ImportgAlice();
-  AliRunLoader* runLoader = 
-    AliRunLoader::GetRunLoader(manager->GetInputStream(0)->GetFolderName());
+  if (!static_cast<AliStream*>(digInp.GetInputStream(0))->ImportgAlice()) {
+    AliError("Error occured while getting gAlice from Input 0");
+    return kFALSE;
+  }
+  AliRunLoader* runLoader = AliRunLoader::GetRunLoader(digInp.GetInputStream(0)->GetFolderName());
   TObjArray* detArray = runLoader->GetAliRun()->Detectors();
   for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
     AliModule* det = (AliModule*) detArray->At(iDet);
     if (!det || !det->IsActive()) continue;
-    if (IsSelected(det->GetName(), detStr) && 
-       !IsSelected(det->GetName(), detExcl)) {
-      AliDigitizer* digitizer = det->CreateDigitizer(manager);
-      
-      if (!digitizer) {
-       AliError(Form("no digitizer for %s", det->GetName()));
-       if (fStopOnError) return kFALSE;
-      } else {
-       digitizer->SetRegionOfInterest(fRegionOfInterest);
-      }
+    if (!IsSelected(det->GetName(), detStr) || IsSelected(det->GetName(), detExcl)) continue;
+    AliDigitizer* digitizer = det->CreateDigitizer(&digInp);
+    if (!digitizer || !digitizer->Init()) {
+      AliError(Form("no digitizer for %s", det->GetName()));
+      if (fStopOnError) return kFALSE;
+      else continue;
     }
+    detArr.AddLast(digitizer);    
+    AliInfo(Form("Created digitizer from SDigits -> Digits for %s", det->GetName()));    
   }
-
+  //
   if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
-    AliError(Form("the following detectors were not found: %s", 
-                  detStr.Data()));
+    AliError(Form("the following detectors were not found: %s", detStr.Data()));
     if (fStopOnError) return kFALSE;
   }
-
-  if (!manager->GetListOfTasks()->IsEmpty()) {
-    AliInfo("executing digitization");
-    manager->Exec("");
-  }
-
-  delete manager;
-
+  //
+  Int_t ndigs = detArr.GetEntriesFast();
+  Int_t eventsCreated = 0;
+  AliRunLoader* outRl =  digInp.GetOutRunLoader();
+  while ((eventsCreated++ < fNEvents) || (fNEvents < 0)) {
+    if (!digInp.ConnectInputTrees()) break;
+    digInp.InitEvent(); //this must be after call of Connect Input tress.
+    if (outRl) outRl->SetEventNumber(eventsCreated-1);
+    static_cast<AliStream*>(digInp.GetInputStream(0))->ImportgAlice(); // use gAlice of the first input stream
+    for (int id=0;id<ndigs;id++) ((AliDigitizer*)detArr[id])->Digitize("");
+    digInp.FinishEvent();
+  };
+  digInp.FinishGlobal();
+  //
   return kTRUE;
 }
 
@@ -1527,7 +1656,7 @@ Bool_t AliSimulation::ConvertRawFilesToDate(const char* dateFileName,
       }
     }
 
-    fprintf(pipe, "GDC DetectorPattern %u\n", detectorPattern);
+    fprintf(pipe, "GDC DetectorPattern %u Timestamp %ld\n", detectorPattern, runLoader->GetHeader()->GetTimeStamp());
     Float_t ldc = 0;
     Int_t prevLDC = -1;
 
@@ -1587,7 +1716,7 @@ Bool_t AliSimulation::ConvertRawFilesToDate(const char* dateFileName,
       AliInfo(Form("List of detectors to be read out: %s",detClust.Data()));
     }
 
-    fprintf(pipe2, "GDC DetectorPattern %u\n", detectorPattern);
+    fprintf(pipe2, "GDC DetectorPattern %u Timestamp %ld\n", detectorPattern, runLoader->GetHeader()->GetTimeStamp());
     Float_t ldc = 0;
     Int_t prevLDC = -1;
 
@@ -1794,7 +1923,7 @@ Bool_t AliSimulation::IsSelected(TString detName, TString& detectors) const
 }
 
 //_____________________________________________________________________________
-Bool_t AliSimulation::ConvertRaw2SDigits(const char* rawDirectory, const char* esdFileName, Int_t N) 
+Int_t AliSimulation::ConvertRaw2SDigits(const char* rawDirectory, const char* esdFileName, Int_t N, Int_t nSkip)
 {
 //
 // Steering routine  to convert raw data in directory rawDirectory/ to fake SDigits. 
@@ -1864,21 +1993,21 @@ Bool_t AliSimulation::ConvertRaw2SDigits(const char* rawDirectory, const char* e
       if (esdFile) {
         esd = new AliESDEvent();
         esdFile->GetObject("esdTree", treeESD);
-        if (treeESD) esd->ReadFromTree(treeESD);
+                 if (treeESD) {
+                         esd->ReadFromTree(treeESD);
+                         if (nSkip>0) {
+                                 AliInfo(Form("Asking to skip first %d ESDs events",nSkip));
+                         } else {
+                                 nSkip=0;
+                         }
+                 }
       }
     }
 
     //
     // Create the RawReader
     TString fileName(rawDirectory);
-    AliRawReader* rawReader = 0x0;
-    if (fileName.EndsWith("/")) {
-      rawReader = new AliRawReaderFile(fileName);
-    } else if (fileName.EndsWith(".root")) {
-      rawReader = new AliRawReaderRoot(fileName);
-    } else if (!fileName.IsNull()) {
-      rawReader = new AliRawReaderDate(fileName);
-    }
+    AliRawReader* rawReader = AliRawReader::Create(fileName.Data());
     if (!rawReader) return (kFALSE);
     
 //     if (!fEquipIdMap.IsNull() && fRawReader)
@@ -1915,7 +2044,8 @@ Bool_t AliSimulation::ConvertRaw2SDigits(const char* rawDirectory, const char* e
        //
        //  If ESD information available obtain reconstructed vertex and store in header.
        if (treeESD) {
-           treeESD->GetEvent(nev);
+               AliInfo(Form("Selected event %d correspond to event %d in raw and to %d in esd",nev,rawReader->GetEventIndex(),nSkip+rawReader->GetEventIndex()));
+           treeESD->GetEvent(nSkip+rawReader->GetEventIndex());
            const AliESDVertex* esdVertex = esd->GetPrimaryVertex();
            Double_t position[3];
            esdVertex->GetXYZ(position);
@@ -1944,7 +2074,7 @@ Bool_t AliSimulation::ConvertRaw2SDigits(const char* rawDirectory, const char* e
     runLoader->WriteHeader("OVERWRITE");
     runLoader->WriteRunLoader();
 
-    return kTRUE;
+    return nev;
 }
 
 //_____________________________________________________________________________
@@ -1976,7 +2106,9 @@ void AliSimulation::FinishRun()
   AliRunLoader::Instance()->CdGAFile();
   gAlice->Write(0,TObject::kOverwrite);//write AliRun
   AliRunLoader::Instance()->Write(0,TObject::kOverwrite);//write RunLoader itself
-  
+  //
+  StoreUsedCDBMaps();
+  //  
   if(gAlice->GetMCApp()) gAlice->GetMCApp()->FinishRun();  
   AliRunLoader::Instance()->Synchronize();
 }
@@ -2267,10 +2399,8 @@ void AliSimulation::WriteGRPEntry()
   AliGRPObject* grpObj = new AliGRPObject();
 
   grpObj->SetRunType("PHYSICS");
-  grpObj->SetTimeStart(0);
-  TDatime curtime;
-  grpObj->SetTimeStart(0);
-  grpObj->SetTimeEnd(curtime.Convert()); 
+  grpObj->SetTimeStart(fTimeStart);
+  grpObj->SetTimeEnd(fTimeEnd); 
   grpObj->SetBeamEnergyIsSqrtSHalfGeV(); // new format of GRP: store sqrt(s)/2 in GeV
 
   const AliGenerator *gen = gAlice->GetMCApp()->Generator();
@@ -2318,6 +2448,7 @@ void AliSimulation::WriteGRPEntry()
   TObjArray *detArray = gAlice->Detectors();
   for (Int_t iDet = 0; iDet < AliDAQ::kNDetectors-1; iDet++) {
     if (detArray->FindObject(AliDAQ::OfflineModuleName(iDet))) {
+      AliDebug(1, Form("Detector #%d found: %s", iDet, AliDAQ::OfflineModuleName(iDet)));
       detectorPattern |= (1 << iDet);
       nDets++;
     }
@@ -2374,4 +2505,56 @@ void AliSimulation::WriteGRPEntry()
   man->SetLock(1, fKey);
 }
 
+//_____________________________________________________________________________
+time_t AliSimulation::GenerateTimeStamp() const
+{
+  // Generate event time-stamp according to
+  // SOR/EOR time from GRP
+  if (fUseTimeStampFromCDB)
+    return fTimeStart + gRandom->Integer(fTimeEnd-fTimeStart);
+  else
+    return 0;
+}
 
+//_____________________________________________________________________________
+void AliSimulation::StoreUsedCDBMaps() const
+{
+  // write in galice.root maps with used CDB paths
+  //
+  const TMap *cdbMap = AliCDBManager::Instance()->GetStorageMap();      
+  const TList *cdbList = AliCDBManager::Instance()->GetRetrievedIds();  
+  //
+  TMap *cdbMapCopy = new TMap(cdbMap->GetEntries());    
+  cdbMapCopy->SetOwner(1);      
+  //  cdbMapCopy->SetName("cdbMap");    
+  TIter iter(cdbMap->GetTable());       
+  //    
+  TPair* pair = 0;      
+  while((pair = dynamic_cast<TPair*> (iter.Next()))){   
+    TObjString* keyStr = dynamic_cast<TObjString*> (pair->Key());       
+    TObjString* valStr = dynamic_cast<TObjString*> (pair->Value());
+    if (keyStr && valStr)
+      cdbMapCopy->Add(new TObjString(keyStr->GetName()), new TObjString(valStr->GetName()));    
+  }     
+  //    
+  TList *cdbListCopy = new TList();     
+  cdbListCopy->SetOwner(1);     
+  //  cdbListCopy->SetName("cdbList");  
+  //
+  TIter iter2(cdbList);         
+  
+  AliCDBId* id=0;
+  while((id = dynamic_cast<AliCDBId*> (iter2.Next()))){         
+    cdbListCopy->Add(new TObjString(id->ToString().Data()));    
+  }     
+  //
+  AliRunLoader::Instance()->CdGAFile();
+  gDirectory->WriteObject(cdbMapCopy,"cdbMap","kSingleKey");
+  gDirectory->WriteObject(cdbListCopy,"cdbList","kSingleKey");  
+  //
+  AliInfo(Form("Stored used OCDB entries as TMap %s and TList %s in %s",
+              cdbMapCopy->GetName(),
+              cdbListCopy->GetName(),
+              fGAliceFileName.Data()));
+  //
+}