New detector AD
[u/mrichter/AliRoot.git] / STEER / STEER / AliSimulation.cxx
index 0c6ab5b..f14ce9d 100644 (file)
@@ -13,7 +13,7 @@
  * provided "as is" without express or implied warranty.                  *
  **************************************************************************/
 
-/* $Id$ */
+/* $Id: AliSimulation.cxx 63204 2013-06-26 13:33:28Z 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",
+// #ifdef MFT_UPGRADE
+//                                                                             ,"MFT"
+// #endif 
+                                                                            "MFT"    // AU
+                                                                           ,"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 +183,7 @@ AliSimulation::AliSimulation(const char* configFileName,
   fDeleteIntermediateFiles(kFALSE),
   fWriteSelRawData(kFALSE),
   fStopOnError(kFALSE),
+  fUseMonitoring(kFALSE),
   fNEvents(1),
   fConfigFileName(configFileName),
   fGAliceFileName("galice.root"),
@@ -370,7 +380,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;
 }
 
@@ -623,6 +633,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;
@@ -715,7 +736,7 @@ Bool_t AliSimulation::Run(Int_t nEvents)
   
   
   // digits -> trigger
-  if (!RunTrigger(fTriggerConfig,fMakeDigits)) {
+  if (!fTriggerConfig.IsNull() && !RunTrigger(fTriggerConfig,fMakeDigits)) {
     if (fStopOnError) return kFALSE;
   }
 
@@ -743,15 +764,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();
 
@@ -972,6 +1004,7 @@ Bool_t AliSimulation::RunSimulation(Int_t nEvents)
   InitCDB();
   AliSysInfo::AddStamp("RunSimulation_InitCDB");
   InitRunNumber();
+
   SetCDBLock();
   AliSysInfo::AddStamp("RunSimulation_SetCDBLock");
   
@@ -983,6 +1016,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()));
@@ -1003,8 +1039,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");
 
 //
@@ -1067,7 +1107,6 @@ Bool_t AliSimulation::RunSimulation(Int_t nEvents)
 
    gMC->SetMagField(TGeoGlobalMagField::Instance()->GetField());
    AliSysInfo::AddStamp("RunSimulation_GetField");
-   
    gAlice->GetMCApp()->Init();
    AliSysInfo::AddStamp("RunSimulation_InitMCApp");
 
@@ -1187,7 +1226,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
@@ -1200,6 +1238,75 @@ Bool_t AliSimulation::RunSimulation(Int_t nEvents)
 }
 
 //_____________________________________________________________________________
+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)
 {
 // run the digitization and produce summable digits
@@ -1260,50 +1367,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;
 }
 
@@ -1547,7 +1660,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;
 
@@ -1607,7 +1720,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;
 
@@ -1814,7 +1927,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. 
@@ -1884,21 +1997,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)
@@ -1935,7 +2048,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);
@@ -1964,7 +2078,7 @@ Bool_t AliSimulation::ConvertRaw2SDigits(const char* rawDirectory, const char* e
     runLoader->WriteHeader("OVERWRITE");
     runLoader->WriteRunLoader();
 
-    return kTRUE;
+    return nev;
 }
 
 //_____________________________________________________________________________
@@ -2336,6 +2450,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++;
     }