]> git.uio.no Git - u/mrichter/AliRoot.git/blob - STEER/STEER/AliSimulation.cxx
Generation of event time-stamps according to GRP SOR/EOR times. The method to active...
[u/mrichter/AliRoot.git] / STEER / STEER / AliSimulation.cxx
1 /**************************************************************************
2  * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
3  *                                                                        *
4  * Author: The ALICE Off-line Project.                                    *
5  * Contributors are mentioned in the code where appropriate.              *
6  *                                                                        *
7  * Permission to use, copy, modify and distribute this software and its   *
8  * documentation strictly for non-commercial purposes is hereby granted   *
9  * without fee, provided that the above copyright notice appears in all   *
10  * copies and that both the copyright notice and this permission notice   *
11  * appear in the supporting documentation. The authors make no claims     *
12  * about the suitability of this software for any purpose. It is          *
13  * provided "as is" without express or implied warranty.                  *
14  **************************************************************************/
15
16 /* $Id$ */
17
18 ///////////////////////////////////////////////////////////////////////////////
19 //                                                                           //
20 // class for running generation, simulation and digitization                 //
21 //                                                                           //
22 // Hits, sdigits and digits are created for all detectors by typing:         //
23 //                                                                           //
24 //   AliSimulation sim;                                                      //
25 //   sim.Run();                                                              //
26 //                                                                           //
27 // The Run method returns kTRUE in case of successful execution.             //
28 // The number of events can be given as argument to the Run method or it     //
29 // can be set by                                                             //
30 //                                                                           //
31 //   sim.SetNumberOfEvents(n);                                               //
32 //                                                                           //
33 // The name of the configuration file can be passed as argument to the       //
34 // AliSimulation constructor or can be specified by                          //
35 //                                                                           //
36 //   sim.SetConfigFile("...");                                               //
37 //                                                                           //
38 // The generation of particles and the simulation of detector hits can be    //
39 // switched on or off by                                                     //
40 //                                                                           //
41 //   sim.SetRunGeneration(kTRUE);   // generation of primary particles       //
42 //   sim.SetRunSimulation(kFALSE);  // but no tracking                       //
43 //                                                                           //
44 // For which detectors sdigits and digits will be created, can be steered    //
45 // by                                                                        //
46 //                                                                           //
47 //   sim.SetMakeSDigits("ALL");     // make sdigits for all detectors        //
48 //   sim.SetMakeDigits("ITS TPC");  // make digits only for ITS and TPC      //
49 //                                                                           //
50 // The argument is a (case sensitive) string with the names of the           //
51 // detectors separated by a space. An empty string ("") can be used to       //
52 // disable the creation of sdigits or digits. The special string "ALL"       //
53 // selects all available detectors. This is the default.                     //
54 //                                                                           //
55 // The creation of digits from hits instead of from sdigits can be selected  //
56 // by                                                                        //
57 //                                                                           //
58 //   sim.SetMakeDigitsFromHits("TRD");                                       //
59 //                                                                           //
60 // The argument is again a string with the selected detectors. Be aware that //
61 // this feature is not available for all detectors and that merging is not   //
62 // possible, when digits are created directly from hits.                     //
63 //                                                                           //
64 // Background events can be merged by calling                                //
65 //                                                                           //
66 //   sim.MergeWith("background/galice.root", 2);                             //
67 //                                                                           //
68 // The first argument is the file name of the background galice file. The    //
69 // second argument is the number of signal events per background event.      //
70 // By default this number is calculated from the number of available         //
71 // background events. MergeWith can be called several times to merge more    //
72 // than two event streams. It is assumed that the sdigits were already       //
73 // produced for the background events.                                       //
74 //                                                                           //
75 // The output of raw data can be switched on by calling                      //
76 //                                                                           //
77 //   sim.SetWriteRawData("MUON");   // write raw data for MUON               //
78 //                                                                           //
79 // The default output format of the raw data are DDL files. They are         //
80 // converted to a DATE file, if a file name is given as second argument.     //
81 // For this conversion the program "dateStream" is required. If the file     //
82 // name has the extension ".root", the DATE file is converted to a root      //
83 // file. The program "alimdc" is used for this purpose. For the conversion   //
84 // to DATE and root format the two conversion programs have to be installed. //
85 // Only the raw data in the final format is kept if the third argument is    //
86 // kTRUE.                                                                    //
87 //                                                                           //
88 // The methods RunSimulation, RunSDigitization, RunDigitization,             //
89 // RunHitsDigitization and WriteRawData can be used to run only parts of     //
90 // the full simulation chain. The creation of raw data DDL files and their   //
91 // conversion to the DATE or root format can be run directly by calling      //
92 // the methods WriteRawFiles, ConvertRawFilesToDate and ConvertDateToRoot.   //
93 //                                                                           //
94 // The default number of events per file, which is usually set in the        //
95 // config file, can be changed for individual detectors and data types       //
96 // by calling                                                                //
97 //                                                                           //
98 //   sim.SetEventsPerFile("PHOS", "Reconstructed Points", 3);                //
99 //                                                                           //
100 // The first argument is the detector, the second one the data type and the  //
101 // last one the number of events per file. Valid data types are "Hits",      //
102 // "Summable Digits", "Digits", "Reconstructed Points" and "Tracks".         //
103 // The number of events per file has to be set before the simulation of      //
104 // hits. Otherwise it has no effect.                                         //
105 //                                                                           //
106 ///////////////////////////////////////////////////////////////////////////////
107
108 #include <TCint.h>
109 #include <TFile.h>
110 #include <TGeoGlobalMagField.h>
111 #include <TGeoManager.h>
112 #include <TObjString.h>
113 #include <TROOT.h>
114 #include <TSystem.h>
115 #include <TVirtualMC.h>
116 #include <TVirtualMCApplication.h>
117 #include <TDatime.h>
118
119 #include "AliAlignObj.h"
120 #include "AliCDBEntry.h"
121 #include "AliCDBManager.h"
122 #include "AliGRPManager.h"
123 #include "AliCDBStorage.h"
124 #include "AliCTPRawData.h"
125 #include "AliCentralTrigger.h"
126 #include "AliCentralTrigger.h"
127 #include "AliCodeTimer.h"
128 #include "AliDAQ.h"
129 #include "AliDigitizer.h"
130 #include "AliESDEvent.h"
131 #include "AliGRPObject.h"
132 #include "AliGenEventHeader.h"
133 #include "AliGenerator.h"
134 #include "AliGeomManager.h"
135 #include "AliHLTSimulation.h"
136 #include "AliHeader.h"
137 #include "AliLego.h"
138 #include "AliLegoGenerator.h"
139 #include "AliLog.h"
140 #include "AliMC.h"
141 #include "AliMagF.h"
142 #include "AliModule.h"
143 #include "AliPDG.h"
144 #include "AliRawReaderDate.h"
145 #include "AliRawReaderFile.h"
146 #include "AliRawReaderRoot.h"
147 #include "AliRun.h"
148 #include "AliRunDigitizer.h"
149 #include "AliRunLoader.h"
150 #include "AliSimulation.h"
151 #include "AliSysInfo.h"
152 #include "AliVertexGenFile.h"
153
154 ClassImp(AliSimulation)
155
156 AliSimulation *AliSimulation::fgInstance = 0;
157 const char* AliSimulation::fgkDetectorName[AliSimulation::fgkNDetectors] = {"ITS", "TPC", "TRD", "TOF", "PHOS", "HMPID", "EMCAL", "MUON", "FMD", "ZDC", "PMD", "T0", "VZERO", "ACORDE", "HLT"};
158
159 //_____________________________________________________________________________
160 AliSimulation::AliSimulation(const char* configFileName,
161                              const char* name, const char* title) :
162   TNamed(name, title),
163
164   fRunGeneration(kTRUE),
165   fRunSimulation(kTRUE),
166   fLoadAlignFromCDB(kTRUE),
167   fLoadAlObjsListOfDets("ALL"),
168   fMakeSDigits("ALL"),
169   fMakeDigits("ALL"),
170   fTriggerConfig(""),
171   fMakeDigitsFromHits(""),
172   fWriteRawData(""),
173   fRawDataFileName(""),
174   fDeleteIntermediateFiles(kFALSE),
175   fWriteSelRawData(kFALSE),
176   fStopOnError(kFALSE),
177   fNEvents(1),
178   fConfigFileName(configFileName),
179   fGAliceFileName("galice.root"),
180   fEventsPerFile(),
181   fBkgrdFileNames(NULL),
182   fAlignObjArray(NULL),
183   fUseBkgrdVertex(kTRUE),
184   fRegionOfInterest(kFALSE),
185   fCDBUri(""),
186   fQARefUri(""), 
187   fSpecCDBUri(),
188   fRun(-1),
189   fSeed(0),
190   fInitCDBCalled(kFALSE),
191   fInitRunNumberCalled(kFALSE),
192   fSetRunNumberFromDataCalled(kFALSE),
193   fEmbeddingFlag(kFALSE),
194   fLego(NULL),
195   fKey(0),
196   fUseVertexFromCDB(0),
197   fUseMagFieldFromGRP(0),
198   fGRPWriteLocation(Form("local://%s", gSystem->pwd())),
199   fUseTimeStampFromCDB(0),
200   fTimeStart(0),
201   fTimeEnd(0),
202   fQADetectors("ALL"),                  
203   fQATasks("ALL"),      
204   fRunQA(kTRUE), 
205   fEventSpecie(AliRecoParam::kDefault),
206   fWriteQAExpertData(kTRUE), 
207   fGeometryFile(),
208   fRunHLT("default"),
209   fpHLT(NULL),
210   fWriteGRPEntry(kTRUE)
211 {
212 // create simulation object with default parameters
213   fgInstance = this;
214   SetGAliceFile("galice.root");
215   
216 // for QA
217         AliQAManager * qam = AliQAManager::QAManager(AliQAv1::kSIMMODE) ; 
218         qam->SetActiveDetectors(fQADetectors) ; 
219         fQATasks = Form("%d %d %d", AliQAv1::kHITS, AliQAv1::kSDIGITS, AliQAv1::kDIGITS) ; 
220         qam->SetTasks(fQATasks) ;       
221 }
222
223 //_____________________________________________________________________________
224 AliSimulation::~AliSimulation()
225 {
226 // clean up
227
228   fEventsPerFile.Delete();
229 //  if(fAlignObjArray) fAlignObjArray->Delete(); // fAlignObjArray->RemoveAll() ???
230 //  delete fAlignObjArray; fAlignObjArray=0;
231
232   if (fBkgrdFileNames) {
233     fBkgrdFileNames->Delete();
234     delete fBkgrdFileNames;
235   }
236
237   fSpecCDBUri.Delete();
238   if (fgInstance==this) fgInstance = 0;
239
240   AliQAManager::QAManager()->ShowQA() ; 
241   AliQAManager::Destroy() ;     
242   AliCodeTimer::Instance()->Print();
243 }
244
245
246 //_____________________________________________________________________________
247 void AliSimulation::SetNumberOfEvents(Int_t nEvents)
248 {
249 // set the number of events for one run
250
251   fNEvents = nEvents;
252 }
253
254 //_____________________________________________________________________________
255 void AliSimulation::InitQA()
256 {
257   // activate a default CDB storage
258   // First check if we have any CDB storage set, because it is used 
259   // to retrieve the calibration and alignment constants
260   
261   if (fInitCDBCalled) return;
262   fInitCDBCalled = kTRUE;
263
264   AliQAManager * qam = AliQAManager::QAManager(AliQAv1::kSIMMODE) ; 
265   qam->SetActiveDetectors(fQADetectors) ; 
266   fQATasks = Form("%d %d %d", AliQAv1::kHITS, AliQAv1::kSDIGITS, AliQAv1::kDIGITS) ; 
267   qam->SetTasks(fQATasks) ;
268         if (fWriteQAExpertData)
269     qam->SetWriteExpert() ; 
270   
271   if (qam->IsDefaultStorageSet()) {
272     AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
273     AliWarning("Default QA reference storage has been already set !");
274     AliWarning(Form("Ignoring the default storage declared in AliSimulation: %s",fQARefUri.Data()));
275     AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
276     fQARefUri = qam->GetDefaultStorage()->GetURI();
277   } else {
278       if (fQARefUri.Length() > 0) {
279         AliDebug(2,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
280         AliDebug(2, Form("Default QA reference storage is set to: %s", fQARefUri.Data()));
281         AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
282       } else {
283         fQARefUri="local://$ALICE_ROOT/QARef";
284         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
285         AliWarning("Default QA reference storage not yet set !!!!");
286         AliWarning(Form("Setting it now to: %s", fQARefUri.Data()));
287         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
288       }
289     qam->SetDefaultStorage(fQARefUri);
290   }
291 }
292
293 //_____________________________________________________________________________
294 void AliSimulation::InitCDB()
295 {
296 // activate a default CDB storage
297 // First check if we have any CDB storage set, because it is used 
298 // to retrieve the calibration and alignment constants
299
300   if (fInitCDBCalled) return;
301   fInitCDBCalled = kTRUE;
302
303   AliCDBManager* man = AliCDBManager::Instance();
304   if (man->IsDefaultStorageSet())
305   {
306     AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
307     AliWarning("Default CDB storage has been already set !");
308     AliWarning(Form("Ignoring the default storage declared in AliSimulation: %s",fCDBUri.Data()));
309     AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
310     fCDBUri = man->GetDefaultStorage()->GetURI();
311   }
312   else {
313     if (fCDBUri.Length() > 0) 
314     {
315         AliDebug(2,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
316         AliDebug(2, Form("Default CDB storage is set to: %s", fCDBUri.Data()));
317         AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
318     } else {
319         fCDBUri="local://$ALICE_ROOT/OCDB";
320         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
321         AliWarning("Default CDB storage not yet set !!!!");
322         AliWarning(Form("Setting it now to: %s", fCDBUri.Data()));
323         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
324                 
325     }
326     man->SetDefaultStorage(fCDBUri);
327   }
328
329   // Now activate the detector specific CDB storage locations
330   for (Int_t i = 0; i < fSpecCDBUri.GetEntriesFast(); i++) {
331     TObject* obj = fSpecCDBUri[i];
332     if (!obj) continue;
333     AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
334     AliDebug(2, Form("Specific CDB storage for %s is set to: %s",obj->GetName(),obj->GetTitle()));
335     AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
336     man->SetSpecificStorage(obj->GetName(), obj->GetTitle());
337   }
338       
339 }
340
341 //_____________________________________________________________________________
342 void AliSimulation::InitRunNumber(){
343 // check run number. If not set, set it to 0 !!!!
344   
345   if (fInitRunNumberCalled) return;
346   fInitRunNumberCalled = kTRUE;
347   
348   AliCDBManager* man = AliCDBManager::Instance();
349   if (man->GetRun() >= 0)
350   {
351         AliFatal(Form("Run number cannot be set in AliCDBManager before start of simulation: "
352                         "Use external variable DC_RUN or AliSimulation::SetRun()!"));
353   }
354     
355   if(fRun >= 0) {
356         AliDebug(2, Form("Setting CDB run number to: %d",fRun));
357   } else {
358         fRun=0;
359         AliWarning(Form("Run number not yet set !!!! Setting it now to: %d",
360                         fRun));
361   }
362   man->SetRun(fRun);
363
364   man->Print();
365
366 }
367
368 //_____________________________________________________________________________
369 void AliSimulation::SetCDBLock() {
370   // Set CDB lock: from now on it is forbidden to reset the run number
371   // or the default storage or to activate any further storage!
372   
373   ULong_t key = AliCDBManager::Instance()->SetLock(1);
374   if (key) fKey = key;
375 }
376
377 //_____________________________________________________________________________
378 void AliSimulation::SetDefaultStorage(const char* uri) {
379   // Store the desired default CDB storage location
380   // Activate it later within the Run() method
381   
382   fCDBUri = uri;
383   
384 }
385
386 //_____________________________________________________________________________
387 void AliSimulation::SetQARefDefaultStorage(const char* uri) {
388   // Store the desired default CDB storage location
389   // Activate it later within the Run() method
390   
391   fQARefUri = uri;
392   AliQAv1::SetQARefStorage(fQARefUri.Data()) ;
393 }
394
395 //_____________________________________________________________________________
396 void AliSimulation::SetSpecificStorage(const char* calibType, const char* uri) {
397 // Store a detector-specific CDB storage location
398 // Activate it later within the Run() method
399
400   AliCDBPath aPath(calibType);
401   if(!aPath.IsValid()){
402         AliError(Form("Not a valid path: %s", calibType));
403         return;
404   }
405
406   TObject* obj = fSpecCDBUri.FindObject(calibType);
407   if (obj) fSpecCDBUri.Remove(obj);
408   fSpecCDBUri.Add(new TNamed(calibType, uri));
409
410 }
411
412 //_____________________________________________________________________________
413 void AliSimulation::SetRunNumber(Int_t run)
414 {
415 // sets run number
416 // Activate it later within the Run() method
417
418         fRun = run;
419 }
420
421 //_____________________________________________________________________________
422 void AliSimulation::SetSeed(Int_t seed)
423 {
424 // sets seed number
425 // Activate it later within the Run() method
426
427         fSeed = seed;
428 }
429
430 //_____________________________________________________________________________
431 Bool_t AliSimulation::SetRunNumberFromData()
432 {
433   // Set the CDB manager run number
434   // The run number is retrieved from gAlice
435
436     if (fSetRunNumberFromDataCalled) return kTRUE;
437     fSetRunNumberFromDataCalled = kTRUE;    
438   
439     AliCDBManager* man = AliCDBManager::Instance();
440     Int_t runData = -1, runCDB = -1;
441   
442     AliRunLoader* runLoader = LoadRun("READ");
443     if (!runLoader) return kFALSE;
444     else {
445         runData = runLoader->GetHeader()->GetRun();
446         delete runLoader;
447     }
448   
449     runCDB = man->GetRun();
450     if(runCDB >= 0) {
451         if (runCDB != runData) {
452                 AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
453                 AliWarning(Form("A run number was previously set in AliCDBManager: %d !", runCDB));
454                 AliWarning(Form("It will be replaced with the run number got from run header: %d !", runData));
455                 AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");    
456         }
457         
458     }
459       
460     man->SetRun(runData);
461     fRun = runData;
462     
463     if(man->GetRun() < 0) {
464         AliError("Run number not properly initalized!");
465         return kFALSE;
466     }
467   
468     man->Print();
469     
470     return kTRUE;
471 }
472
473 //_____________________________________________________________________________
474 void AliSimulation::SetConfigFile(const char* fileName)
475 {
476 // set the name of the config file
477
478   fConfigFileName = fileName;
479 }
480
481 //_____________________________________________________________________________
482 void AliSimulation::SetGAliceFile(const char* fileName)
483 {
484 // set the name of the galice file
485 // the path is converted to an absolute one if it is relative
486
487   fGAliceFileName = fileName;
488   if (!gSystem->IsAbsoluteFileName(fGAliceFileName)) {
489     char* absFileName = gSystem->ConcatFileName(gSystem->WorkingDirectory(),
490                                                 fGAliceFileName);
491     fGAliceFileName = absFileName;
492     delete[] absFileName;
493   }
494
495   AliDebug(2, Form("galice file name set to %s", fileName));
496 }
497
498 //_____________________________________________________________________________
499 void AliSimulation::SetEventsPerFile(const char* detector, const char* type, 
500                                      Int_t nEvents)
501 {
502 // set the number of events per file for the given detector and data type
503 // ("Hits", "Summable Digits", "Digits", "Reconstructed Points" or "Tracks")
504
505   TNamed* obj = new TNamed(detector, type);
506   obj->SetUniqueID(nEvents);
507   fEventsPerFile.Add(obj);
508 }
509
510 //_____________________________________________________________________________
511 Bool_t AliSimulation::MisalignGeometry(AliRunLoader *runLoader)
512 {
513   // Read the alignment objects from CDB.
514   // Each detector is supposed to have the
515   // alignment objects in DET/Align/Data CDB path.
516   // All the detector objects are then collected,
517   // sorted by geometry level (starting from ALIC) and
518   // then applied to the TGeo geometry.
519   // Finally an overlaps check is performed.
520
521   if (!AliGeomManager::GetGeometry() || !AliGeomManager::GetGeometry()->IsClosed()) {
522     AliError("Can't apply the misalignment! Geometry is not loaded or it is still opened!");
523     return kFALSE;
524   }  
525   
526   // initialize CDB storage, run number, set CDB lock
527   InitCDB();
528 //  if (!SetRunNumberFromData()) if (fStopOnError) return kFALSE;
529   SetCDBLock();
530     
531   Bool_t delRunLoader = kFALSE;
532   if (!runLoader) {
533     runLoader = LoadRun("READ");
534     if (!runLoader) return kFALSE;
535     delRunLoader = kTRUE;
536   }
537   
538   // Export ideal geometry 
539   if(!IsGeometryFromFile()) AliGeomManager::GetGeometry()->Export("geometry.root");
540
541   // Load alignment data from CDB and apply to geometry through AliGeomManager
542   if(fLoadAlignFromCDB){
543     
544     TString detStr = fLoadAlObjsListOfDets;
545     TString loadAlObjsListOfDets = "";
546     
547     TObjArray* detArray = runLoader->GetAliRun()->Detectors();
548     for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
549       AliModule* det = (AliModule*) detArray->At(iDet);
550       if (!det || !det->IsActive()) continue;
551       if (IsSelected(det->GetName(), detStr)) {
552         //add det to list of dets to be aligned from CDB
553         loadAlObjsListOfDets += det->GetName();
554         loadAlObjsListOfDets += " ";
555       }
556     } // end loop over detectors
557     loadAlObjsListOfDets.Prepend("GRP "); //add alignment objects for non-sensitive modules
558     AliGeomManager::ApplyAlignObjsFromCDB(loadAlObjsListOfDets.Data());
559   }else{
560     // Check if the array with alignment objects was
561     // provided by the user. If yes, apply the objects
562     // to the present TGeo geometry
563     if (fAlignObjArray) {
564       if (AliGeomManager::ApplyAlignObjsToGeom(*fAlignObjArray) == kFALSE) {
565         AliError("The misalignment of one or more volumes failed!"
566                  "Compare the list of simulated detectors and the list of detector alignment data!");
567         if (delRunLoader) delete runLoader;
568         return kFALSE;
569       }
570     }
571   }
572
573   // Update the internal geometry of modules (ITS needs it)
574   TString detStr = fLoadAlObjsListOfDets;
575   TObjArray* detArray = runLoader->GetAliRun()->Detectors();
576   for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
577
578     AliModule* det = (AliModule*) detArray->At(iDet);
579     if (!det || !det->IsActive()) continue;
580     if (IsSelected(det->GetName(), detStr)) {
581       det->UpdateInternalGeometry();
582     }
583   } // end loop over detectors
584
585
586   if (delRunLoader) delete runLoader;
587
588   return kTRUE;
589 }
590
591 //_____________________________________________________________________________
592 void AliSimulation::MergeWith(const char* fileName, Int_t nSignalPerBkgrd)
593 {
594 // add a file with background events for merging
595
596   TObjString* fileNameStr = new TObjString(fileName);
597   fileNameStr->SetUniqueID(nSignalPerBkgrd);
598   if (!fBkgrdFileNames) fBkgrdFileNames = new TObjArray;
599   fBkgrdFileNames->Add(fileNameStr);
600 }
601
602 void AliSimulation::EmbedInto(const char* fileName, Int_t nSignalPerBkgrd)
603 {
604 // add a file with background events for embeddin
605   MergeWith(fileName, nSignalPerBkgrd);
606   fEmbeddingFlag = kTRUE;
607 }
608
609 //_____________________________________________________________________________
610 Bool_t AliSimulation::Run(Int_t nEvents)
611 {
612 // run the generation, simulation and digitization
613
614  
615   AliCodeTimerAuto("",0)
616   AliSysInfo::AddStamp("Start_Run");
617   
618   // Load run number and seed from environmental vars
619   ProcessEnvironmentVars();
620   AliSysInfo::AddStamp("ProcessEnvironmentVars");
621
622   gRandom->SetSeed(fSeed);
623    
624   if (nEvents > 0) fNEvents = nEvents;
625
626   // create and setup the HLT instance
627   if (!fRunHLT.IsNull() && !CreateHLT()) {
628     if (fStopOnError) return kFALSE;
629     // disable HLT
630     fRunHLT="";
631   }
632   
633   // generation and simulation -> hits
634   if (fRunGeneration) {
635     if (!RunSimulation()) if (fStopOnError) return kFALSE;
636   }
637   AliSysInfo::AddStamp("RunSimulation");
638            
639   // initialize CDB storage from external environment
640   // (either CDB manager or AliSimulation setters),
641   // if not already done in RunSimulation()
642   InitCDB();
643   AliSysInfo::AddStamp("InitCDB");
644   
645   // Set run number in CDBManager from data 
646   // From this point on the run number must be always loaded from data!
647   if (!SetRunNumberFromData()) if (fStopOnError) return kFALSE;
648   
649   // Set CDB lock: from now on it is forbidden to reset the run number
650   // or the default storage or to activate any further storage!
651   SetCDBLock();
652
653   // If RunSimulation was not called, load the geometry and misalign it
654   if (!AliGeomManager::GetGeometry()) {
655     // Initialize the geometry manager
656     AliGeomManager::LoadGeometry("geometry.root");
657     AliSysInfo::AddStamp("GetGeometry");
658 //    // Check that the consistency of symbolic names for the activated subdetectors
659 //    // in the geometry loaded by AliGeomManager
660 //    AliRunLoader* runLoader = LoadRun("READ");
661 //    if (!runLoader) return kFALSE;
662 //
663 //    TString detsToBeChecked = "";
664 //    TObjArray* detArray = runLoader->GetAliRun()->Detectors();
665 //    for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
666 //      AliModule* det = (AliModule*) detArray->At(iDet);
667 //      if (!det || !det->IsActive()) continue;
668 //      detsToBeChecked += det->GetName();
669 //      detsToBeChecked += " ";
670 //    } // end loop over detectors
671 //    if(!AliGeomManager::CheckSymNamesLUT(detsToBeChecked.Data()))
672     if(!AliGeomManager::CheckSymNamesLUT("ALL"))
673         AliFatalClass("Current loaded geometry differs in the definition of symbolic names!");
674         
675     if (!AliGeomManager::GetGeometry()) if (fStopOnError) return kFALSE;
676     // Misalign geometry
677     if(!MisalignGeometry()) if (fStopOnError) return kFALSE;
678   }
679   AliSysInfo::AddStamp("MissalignGeometry");
680
681
682   // hits -> summable digits
683   AliSysInfo::AddStamp("Start_sdigitization");
684   if (!fMakeSDigits.IsNull()) {
685     if (!RunSDigitization(fMakeSDigits)) if (fStopOnError) return kFALSE;
686  
687   }
688   AliSysInfo::AddStamp("Stop_sdigitization");
689   
690   AliSysInfo::AddStamp("Start_digitization");  
691   // summable digits -> digits  
692   if (!fMakeDigits.IsNull()) {
693     if (!RunDigitization(fMakeDigits, fMakeDigitsFromHits)) {
694       if (fStopOnError) return kFALSE;
695     }
696    }
697   AliSysInfo::AddStamp("Stop_digitization");
698
699   
700   
701   // hits -> digits
702   if (!fMakeDigitsFromHits.IsNull()) {
703     if (fBkgrdFileNames && (fBkgrdFileNames->GetEntriesFast() > 0)) {
704       AliWarning(Form("Merging and direct creation of digits from hits " 
705                  "was selected for some detectors. "
706                  "No merging will be done for the following detectors: %s",
707                  fMakeDigitsFromHits.Data()));
708     }
709     if (!RunHitsDigitization(fMakeDigitsFromHits)) {
710       if (fStopOnError) return kFALSE;
711     }
712   }
713
714   AliSysInfo::AddStamp("Hits2Digits");
715   
716   
717   // digits -> trigger
718   if (!RunTrigger(fTriggerConfig,fMakeDigits)) {
719     if (fStopOnError) return kFALSE;
720   }
721
722   AliSysInfo::AddStamp("RunTrigger");
723   
724   
725   // digits -> raw data
726   if (!fWriteRawData.IsNull()) {
727     if (!WriteRawData(fWriteRawData, fRawDataFileName, 
728                       fDeleteIntermediateFiles,fWriteSelRawData)) {
729       if (fStopOnError) return kFALSE;
730     }
731   }
732
733   AliSysInfo::AddStamp("WriteRaw");
734   
735   // run HLT simulation on simulated digit data if raw data is not
736   // simulated, otherwise its called as part of WriteRawData
737   if (!fRunHLT.IsNull() && fWriteRawData.IsNull()) {
738     if (!RunHLT()) {
739       if (fStopOnError) return kFALSE;
740     }
741   }
742
743   AliSysInfo::AddStamp("RunHLT");
744   
745   //QA
746         if (fRunQA) {
747                 Bool_t rv = RunQA() ; 
748                 if (!rv)
749                         if (fStopOnError) 
750                                 return kFALSE ;         
751         }
752
753   AliSysInfo::AddStamp("RunQA");
754
755   // Cleanup of CDB manager: cache and active storages!
756   AliCDBManager::Instance()->ClearCache();
757
758   return kTRUE;
759 }
760
761 //_______________________________________________________________________
762 Bool_t AliSimulation::RunLego(const char *setup, Int_t nc1, Float_t c1min,
763                      Float_t c1max,Int_t nc2,Float_t c2min,Float_t c2max,
764                      Float_t rmin,Float_t rmax,Float_t zmax, AliLegoGenerator* gener, Int_t nev)
765 {
766   //
767   // Generates lego plots of:
768   //    - radiation length map phi vs theta
769   //    - radiation length map phi vs eta
770   //    - interaction length map
771   //    - g/cm2 length map
772   //
773   //  ntheta    bins in theta, eta
774   //  themin    minimum angle in theta (degrees)
775   //  themax    maximum angle in theta (degrees)
776   //  nphi      bins in phi
777   //  phimin    minimum angle in phi (degrees)
778   //  phimax    maximum angle in phi (degrees)
779   //  rmin      minimum radius
780   //  rmax      maximum radius
781   //  
782   //
783   //  The number of events generated = ntheta*nphi
784   //  run input parameters in macro setup (default="Config.C")
785   //
786   //  Use macro "lego.C" to visualize the 3 lego plots in spherical coordinates
787   //Begin_Html
788   /*
789     <img src="picts/AliRunLego1.gif">
790   */
791   //End_Html
792   //Begin_Html
793   /*
794     <img src="picts/AliRunLego2.gif">
795   */
796   //End_Html
797   //Begin_Html
798   /*
799     <img src="picts/AliRunLego3.gif">
800   */
801   //End_Html
802   //
803
804 // run the generation and simulation
805
806   AliCodeTimerAuto("",0)
807
808   // initialize CDB storage and run number from external environment
809   // (either CDB manager or AliSimulation setters)
810   InitCDB();
811   InitRunNumber();
812   SetCDBLock();
813   
814   if (!gAlice) {
815     AliError("no gAlice object. Restart aliroot and try again.");
816     return kFALSE;
817   }
818   if (gAlice->Modules()->GetEntries() > 0) {
819     AliError("gAlice was already run. Restart aliroot and try again.");
820     return kFALSE;
821   }
822
823   AliInfo(Form("initializing gAlice with config file %s",
824           fConfigFileName.Data()));
825
826   // Number of events 
827     if (nev == -1) nev  = nc1 * nc2;
828     
829   // check if initialisation has been done
830   // If runloader has been initialized, set the number of events per file to nc1 * nc2
831     
832   // Set new generator
833   if (!gener) gener  = new AliLegoGenerator();
834   //
835   // Configure Generator
836
837   gener->SetRadiusRange(rmin, rmax);
838   gener->SetZMax(zmax);
839   gener->SetCoor1Range(nc1, c1min, c1max);
840   gener->SetCoor2Range(nc2, c2min, c2max);
841   
842   
843   //Create Lego object  
844   fLego = new AliLego("lego",gener);
845
846   //__________________________________________________________________________
847
848   gAlice->Announce();
849
850   gROOT->LoadMacro(setup);
851   gInterpreter->ProcessLine(gAlice->GetConfigFunction());
852
853   if(AliCDBManager::Instance()->GetRun() >= 0) { 
854     SetRunNumber(AliCDBManager::Instance()->GetRun());
855   } else {
856     AliWarning("Run number not initialized!!");
857   }
858
859   AliRunLoader::Instance()->CdGAFile();
860   
861   AliPDG::AddParticlesToPdgDataBase();  
862   
863   gMC->SetMagField(TGeoGlobalMagField::Instance()->GetField());
864
865   gAlice->GetMCApp()->Init();
866   
867   
868   //Must be here because some MCs (G4) adds detectors here and not in Config.C
869   gAlice->InitLoaders();
870   AliRunLoader::Instance()->MakeTree("E");
871   
872   //
873   // Save stuff at the beginning of the file to avoid file corruption
874   AliRunLoader::Instance()->CdGAFile();
875   gAlice->Write();
876
877   //Save current generator
878   AliGenerator *gen=gAlice->GetMCApp()->Generator();
879   gAlice->GetMCApp()->ResetGenerator(gener);
880   //Prepare MC for Lego Run
881   gMC->InitLego();
882   
883   //Run Lego Object
884   
885   
886   AliRunLoader::Instance()->SetNumberOfEventsPerFile(nev);
887   gMC->ProcessRun(nev);
888   
889   // End of this run, close files
890   FinishRun();
891   // Restore current generator
892   gAlice->GetMCApp()->ResetGenerator(gen);
893   // Delete Lego Object
894   delete fLego;
895
896   return kTRUE;
897 }
898
899 //_____________________________________________________________________________
900 Bool_t AliSimulation::RunTrigger(const char* config, const char* detectors)
901 {
902   // run the trigger
903
904   AliCodeTimerAuto("",0)
905
906   // initialize CDB storage from external environment
907   // (either CDB manager or AliSimulation setters),
908   // if not already done in RunSimulation()
909   InitCDB();
910   
911   // Set run number in CDBManager from data 
912   // From this point on the run number must be always loaded from data!
913   if (!SetRunNumberFromData()) if (fStopOnError) return kFALSE;
914   
915   // Set CDB lock: from now on it is forbidden to reset the run number
916   // or the default storage or to activate any further storage!
917   SetCDBLock();
918    
919    AliRunLoader* runLoader = LoadRun("READ");
920    if (!runLoader) return kFALSE;
921    TString trconfiguration = config;
922
923    if (trconfiguration.IsNull()) {
924      if(!fTriggerConfig.IsNull()) {
925        trconfiguration = fTriggerConfig;
926      }
927      else
928        AliWarning("No trigger descriptor is specified. Loading the one that is in the CDB.");
929    }
930
931    runLoader->MakeTree( "GG" );
932    AliCentralTrigger* aCTP = runLoader->GetTrigger();
933    // Load Configuration
934    if (!aCTP->LoadConfiguration( trconfiguration ))
935      return kFALSE;
936
937    // digits -> trigger
938    if( !aCTP->RunTrigger( runLoader , detectors ) ) {
939       if (fStopOnError) {
940         //  delete aCTP;
941         return kFALSE;
942       }
943    }
944
945    delete runLoader;
946
947    return kTRUE;
948 }
949
950 //_____________________________________________________________________________
951 Bool_t AliSimulation::WriteTriggerRawData()
952 {
953   // Writes the CTP (trigger) DDL raw data
954   // Details of the format are given in the
955   // trigger TDR - pages 134 and 135.
956   AliCTPRawData writer;
957   writer.RawData();
958
959   return kTRUE;
960 }
961
962 //_____________________________________________________________________________
963 Bool_t AliSimulation::RunSimulation(Int_t nEvents)
964 {
965 // run the generation and simulation
966
967   AliCodeTimerAuto("",0)
968
969   // initialize CDB storage and run number from external environment
970   // (either CDB manager or AliSimulation setters)
971   AliSysInfo::AddStamp("RunSimulation_Begin");
972   InitCDB();
973   AliSysInfo::AddStamp("RunSimulation_InitCDB");
974   InitRunNumber();
975   SetCDBLock();
976   AliSysInfo::AddStamp("RunSimulation_SetCDBLock");
977   
978   if (!gAlice) {
979     AliError("no gAlice object. Restart aliroot and try again.");
980     return kFALSE;
981   }
982   if (gAlice->Modules()->GetEntries() > 0) {
983     AliError("gAlice was already run. Restart aliroot and try again.");
984     return kFALSE;
985   }
986
987   AliInfo(Form("initializing gAlice with config file %s",
988           fConfigFileName.Data()));
989
990   //
991   // Initialize ALICE Simulation run
992   //
993   gAlice->Announce();
994
995   //
996   // If requested set the mag. field from the GRP entry.
997   // After this the field is loccked and cannot be changed by Config.C
998   if (fUseMagFieldFromGRP) {
999       AliGRPManager grpM;
1000       grpM.ReadGRPEntry();
1001       grpM.SetMagField();
1002       AliInfo("Field is locked now. It cannot be changed in Config.C");
1003   }
1004 //
1005 // Execute Config.C
1006   gROOT->LoadMacro(fConfigFileName.Data());
1007   gInterpreter->ProcessLine(gAlice->GetConfigFunction());
1008   AliSysInfo::AddStamp("RunSimulation_Config");
1009
1010 //
1011 // If requested obtain the vertex position and vertex sigma_z from the CDB
1012 // This overwrites the settings from the Config.C  
1013   if (fUseVertexFromCDB) {
1014       Double_t vtxPos[3] = {0., 0., 0.}; 
1015       Double_t vtxSig[3] = {0., 0., 0.};
1016       AliCDBEntry* entry = AliCDBManager::Instance()->Get("GRP/Calib/MeanVertex");
1017       if (entry) {
1018           AliESDVertex* vertex = dynamic_cast<AliESDVertex*> (entry->GetObject());
1019           if (vertex) {
1020               if(vertex->GetXRes()>2.8) { // > pipe radius --> it's a dummy object, don't use it 
1021                   entry = AliCDBManager::Instance()->Get("GRP/Calib/MeanVertexSPD");
1022                   if (entry) vertex = dynamic_cast<AliESDVertex*> (entry->GetObject());
1023               }
1024           }
1025           if (vertex) {
1026               vertex->GetXYZ(vtxPos);
1027               vertex->GetSigmaXYZ(vtxSig);
1028               AliInfo("Overwriting Config.C vertex settings !");
1029               AliInfo(Form("Vertex position from OCDB entry: x = %13.3f, y = %13.3f, z = %13.3f (sigma = %13.3f)\n",
1030                            vtxPos[0], vtxPos[1], vtxPos[2], vtxSig[2]));
1031               
1032               AliGenerator *gen = gAlice->GetMCApp()->Generator();
1033               gen->SetOrigin(vtxPos[0], vtxPos[1], vtxPos[2]);   // vertex position
1034               gen->SetSigmaZ(vtxSig[2]);
1035           }
1036       }
1037   }
1038
1039   // If requested we take the SOR and EOR time-stamps from the GRP and use them
1040   // in order to generate the event time-stamps
1041   if (fUseTimeStampFromCDB) {
1042     AliGRPManager grpM;
1043     grpM.ReadGRPEntry();
1044     const AliGRPObject *grpObj = grpM.GetGRPData();
1045     if (!grpObj || (grpObj->GetTimeEnd() <= grpObj->GetTimeStart())) {
1046       AliError("Missing GRP or bad SOR/EOR time-stamps! Switching off the time-stamp generation from GRP!");
1047       fTimeStart = fTimeEnd = 0;
1048       fUseTimeStampFromCDB = kFALSE;
1049     }
1050     else {
1051       fTimeStart = grpObj->GetTimeStart();
1052       fTimeEnd = grpObj->GetTimeEnd();
1053     }
1054   }
1055   
1056   if(AliCDBManager::Instance()->GetRun() >= 0) { 
1057     AliRunLoader::Instance()->SetRunNumber(AliCDBManager::Instance()->GetRun());
1058     AliRunLoader::Instance()->SetNumberOfEventsPerRun(fNEvents);
1059   } else {
1060         AliWarning("Run number not initialized!!");
1061   }
1062   
1063    AliRunLoader::Instance()->CdGAFile();
1064    
1065
1066    AliPDG::AddParticlesToPdgDataBase();  
1067
1068    gMC->SetMagField(TGeoGlobalMagField::Instance()->GetField());
1069    AliSysInfo::AddStamp("RunSimulation_GetField");
1070    
1071    gAlice->GetMCApp()->Init();
1072    AliSysInfo::AddStamp("RunSimulation_InitMCApp");
1073
1074    //Must be here because some MCs (G4) adds detectors here and not in Config.C
1075    gAlice->InitLoaders();
1076    AliRunLoader::Instance()->MakeTree("E");
1077    AliRunLoader::Instance()->LoadKinematics("RECREATE");
1078    AliRunLoader::Instance()->LoadTrackRefs("RECREATE");
1079    AliRunLoader::Instance()->LoadHits("all","RECREATE");
1080    //
1081    // Save stuff at the beginning of the file to avoid file corruption
1082    AliRunLoader::Instance()->CdGAFile();
1083    gAlice->Write();
1084    gAlice->SetEventNrInRun(-1); //important - we start Begin event from increasing current number in run
1085    AliSysInfo::AddStamp("RunSimulation_InitLoaders");
1086   //___________________________________________________________________________________________
1087   
1088   AliSysInfo::AddStamp("RunSimulation_TriggerDescriptor");
1089
1090   // Set run number in CDBManager
1091   AliInfo(Form("Run number: %d",AliCDBManager::Instance()->GetRun()));
1092
1093   AliRunLoader* runLoader = AliRunLoader::Instance();
1094   if (!runLoader) {
1095              AliError(Form("gAlice has no run loader object. "
1096                              "Check your config file: %s", fConfigFileName.Data()));
1097              return kFALSE;
1098   }
1099   SetGAliceFile(runLoader->GetFileName());
1100       
1101   // Misalign geometry
1102 #if ROOT_VERSION_CODE < 331527
1103   AliGeomManager::SetGeometry(gGeoManager);
1104   
1105   // Check that the consistency of symbolic names for the activated subdetectors
1106   // in the geometry loaded by AliGeomManager
1107   TString detsToBeChecked = "";
1108   TObjArray* detArray = runLoader->GetAliRun()->Detectors();
1109   for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
1110     AliModule* det = (AliModule*) detArray->At(iDet);
1111     if (!det || !det->IsActive()) continue;
1112     detsToBeChecked += det->GetName();
1113     detsToBeChecked += " ";
1114   } // end loop over detectors
1115   if(!AliGeomManager::CheckSymNamesLUT(detsToBeChecked.Data()))
1116     AliFatalClass("Current loaded geometry differs in the definition of symbolic names!");
1117   MisalignGeometry(runLoader);
1118   AliSysInfo::AddStamp("RunSimulation_MisalignGeometry");
1119 #endif
1120
1121 //   AliRunLoader* runLoader = AliRunLoader::Instance();
1122 //   if (!runLoader) {
1123 //     AliError(Form("gAlice has no run loader object. "
1124 //                   "Check your config file: %s", fConfigFileName.Data()));
1125 //     return kFALSE;
1126 //   }
1127 //   SetGAliceFile(runLoader->GetFileName());
1128
1129   if (!gAlice->GetMCApp()->Generator()) {
1130     AliError(Form("gAlice has no generator object. "
1131                   "Check your config file: %s", fConfigFileName.Data()));
1132     return kFALSE;
1133   }
1134
1135   // Write GRP entry corresponding to the setting found in Cofig.C
1136   if (fWriteGRPEntry)
1137     WriteGRPEntry();
1138   AliSysInfo::AddStamp("RunSimulation_WriteGRP");
1139
1140   if (nEvents <= 0) nEvents = fNEvents;
1141
1142   // get vertex from background file in case of merging
1143   if (fUseBkgrdVertex &&
1144       fBkgrdFileNames && (fBkgrdFileNames->GetEntriesFast() > 0)) {
1145     Int_t signalPerBkgrd = GetNSignalPerBkgrd(nEvents);
1146     const char* fileName = ((TObjString*)
1147                             (fBkgrdFileNames->At(0)))->GetName();
1148     AliInfo(Form("The vertex will be taken from the background "
1149                  "file %s with nSignalPerBackground = %d", 
1150                  fileName, signalPerBkgrd));
1151     AliVertexGenFile* vtxGen = new AliVertexGenFile(fileName, signalPerBkgrd);
1152     gAlice->GetMCApp()->Generator()->SetVertexGenerator(vtxGen);
1153   }
1154
1155   if (!fRunSimulation) {
1156     gAlice->GetMCApp()->Generator()->SetTrackingFlag(0);
1157   }
1158
1159   // set the number of events per file for given detectors and data types
1160   for (Int_t i = 0; i < fEventsPerFile.GetEntriesFast(); i++) {
1161     if (!fEventsPerFile[i]) continue;
1162     const char* detName = fEventsPerFile[i]->GetName();
1163     const char* typeName = fEventsPerFile[i]->GetTitle();
1164     TString loaderName(detName);
1165     loaderName += "Loader";
1166     AliLoader* loader = runLoader->GetLoader(loaderName);
1167     if (!loader) {
1168       AliError(Form("RunSimulation no loader for %s found\n Number of events per file not set for %s %s", 
1169                     detName, typeName, detName));
1170       continue;
1171     }
1172     AliDataLoader* dataLoader = 
1173       loader->GetDataLoader(typeName);
1174     if (!dataLoader) {
1175       AliError(Form("no data loader for %s found\n"
1176                     "Number of events per file not set for %s %s", 
1177                     typeName, detName, typeName));
1178       continue;
1179     }
1180     dataLoader->SetNumberOfEventsPerFile(fEventsPerFile[i]->GetUniqueID());
1181     AliDebug(1, Form("number of events per file set to %d for %s %s",
1182                      fEventsPerFile[i]->GetUniqueID(), detName, typeName));
1183   }
1184
1185   AliInfo("running gAlice");
1186   AliSysInfo::AddStamp("Start_ProcessRun");
1187
1188   // Create the Root Tree with one branch per detector
1189   //Hits moved to begin event -> now we are crating separate tree for each event
1190
1191   gMC->ProcessRun(nEvents);
1192
1193   // End of this run, close files
1194   if(nEvents>0) FinishRun();
1195
1196   AliSysInfo::AddStamp("Stop_ProcessRun");
1197   delete runLoader;
1198
1199   return kTRUE;
1200 }
1201
1202 //_____________________________________________________________________________
1203 Bool_t AliSimulation::RunSDigitization(const char* detectors)
1204 {
1205 // run the digitization and produce summable digits
1206   static Int_t eventNr=0;
1207   AliCodeTimerAuto("",0) ;
1208
1209   // initialize CDB storage, run number, set CDB lock
1210   InitCDB();
1211   if (!SetRunNumberFromData()) if (fStopOnError) return kFALSE;
1212   SetCDBLock();
1213   
1214   AliRunLoader* runLoader = LoadRun();
1215   if (!runLoader) return kFALSE;
1216
1217   TString detStr = detectors;
1218   TObjArray* detArray = runLoader->GetAliRun()->Detectors();
1219   for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
1220     AliModule* det = (AliModule*) detArray->At(iDet);
1221     if (!det || !det->IsActive()) continue;
1222     if (IsSelected(det->GetName(), detStr)) {
1223       AliInfo(Form("creating summable digits for %s", det->GetName()));
1224       AliCodeTimerStart(Form("creating summable digits for %s", det->GetName()));
1225       det->Hits2SDigits();
1226       AliCodeTimerStop(Form("creating summable digits for %s", det->GetName()));
1227       AliSysInfo::AddStamp(Form("Digit_%s_%d",det->GetName(),eventNr), 0,1, eventNr);
1228     }
1229   }
1230
1231   if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
1232     AliError(Form("the following detectors were not found: %s",
1233                   detStr.Data()));
1234     if (fStopOnError) return kFALSE;
1235   }
1236   eventNr++;
1237   delete runLoader;
1238
1239   return kTRUE;
1240 }
1241
1242
1243 //_____________________________________________________________________________
1244 Bool_t AliSimulation::RunDigitization(const char* detectors, 
1245                                       const char* excludeDetectors)
1246 {
1247 // run the digitization and produce digits from sdigits
1248
1249   AliCodeTimerAuto("",0)
1250
1251   // initialize CDB storage, run number, set CDB lock
1252   InitCDB();
1253   if (!SetRunNumberFromData()) if (fStopOnError) return kFALSE;
1254   SetCDBLock();
1255   
1256   delete AliRunLoader::Instance();
1257   delete gAlice;
1258   gAlice = NULL;
1259
1260   Int_t nStreams = 1;
1261   if (fBkgrdFileNames) nStreams = fBkgrdFileNames->GetEntriesFast() + 1;
1262   Int_t signalPerBkgrd = GetNSignalPerBkgrd();
1263   AliRunDigitizer* manager = new AliRunDigitizer(nStreams, signalPerBkgrd);
1264   // manager->SetEmbeddingFlag(fEmbeddingFlag);
1265   manager->SetInputStream(0, fGAliceFileName.Data());
1266   for (Int_t iStream = 1; iStream < nStreams; iStream++) {
1267     const char* fileName = ((TObjString*)
1268                             (fBkgrdFileNames->At(iStream-1)))->GetName();
1269     manager->SetInputStream(iStream, fileName);
1270   }
1271
1272   TString detStr = detectors;
1273   TString detExcl = excludeDetectors;
1274   manager->GetInputStream(0)->ImportgAlice();
1275   AliRunLoader* runLoader = 
1276     AliRunLoader::GetRunLoader(manager->GetInputStream(0)->GetFolderName());
1277   TObjArray* detArray = runLoader->GetAliRun()->Detectors();
1278   for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
1279     AliModule* det = (AliModule*) detArray->At(iDet);
1280     if (!det || !det->IsActive()) continue;
1281     if (IsSelected(det->GetName(), detStr) && 
1282         !IsSelected(det->GetName(), detExcl)) {
1283       AliDigitizer* digitizer = det->CreateDigitizer(manager);
1284       
1285       if (!digitizer) {
1286         AliError(Form("no digitizer for %s", det->GetName()));
1287         if (fStopOnError) return kFALSE;
1288       } else {
1289         digitizer->SetRegionOfInterest(fRegionOfInterest);
1290       }
1291     }
1292   }
1293
1294   if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
1295     AliError(Form("the following detectors were not found: %s", 
1296                   detStr.Data()));
1297     if (fStopOnError) return kFALSE;
1298   }
1299
1300   if (!manager->GetListOfTasks()->IsEmpty()) {
1301     AliInfo("executing digitization");
1302     manager->Exec("");
1303   }
1304
1305   delete manager;
1306
1307   return kTRUE;
1308 }
1309
1310 //_____________________________________________________________________________
1311 Bool_t AliSimulation::RunHitsDigitization(const char* detectors)
1312 {
1313 // run the digitization and produce digits from hits
1314
1315   AliCodeTimerAuto("",0)
1316
1317   // initialize CDB storage, run number, set CDB lock
1318   InitCDB();
1319   if (!SetRunNumberFromData()) if (fStopOnError) return kFALSE;
1320   SetCDBLock();
1321   
1322   AliRunLoader* runLoader = LoadRun("READ");
1323   if (!runLoader) return kFALSE;
1324
1325   TString detStr = detectors;
1326   TObjArray* detArray = runLoader->GetAliRun()->Detectors();
1327   for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
1328     AliModule* det = (AliModule*) detArray->At(iDet);
1329     if (!det || !det->IsActive()) continue;
1330     if (IsSelected(det->GetName(), detStr)) {
1331       AliInfo(Form("creating digits from hits for %s", det->GetName()));
1332       det->Hits2Digits();
1333     }
1334   }
1335
1336   if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
1337     AliError(Form("the following detectors were not found: %s", 
1338                   detStr.Data()));
1339     if (fStopOnError) return kFALSE;
1340   }
1341
1342   return kTRUE;
1343 }
1344
1345 //_____________________________________________________________________________
1346 Bool_t AliSimulation::WriteRawData(const char* detectors, 
1347                                    const char* fileName,
1348                                    Bool_t deleteIntermediateFiles,
1349                                    Bool_t selrawdata)
1350 {
1351 // convert the digits to raw data
1352 // First DDL raw data files for the given detectors are created.
1353 // If a file name is given, the DDL files are then converted to a DATE file.
1354 // If deleteIntermediateFiles is true, the DDL raw files are deleted 
1355 // afterwards.
1356 // If the file name has the extension ".root", the DATE file is converted
1357 // to a root file.
1358 // If deleteIntermediateFiles is true, the DATE file is deleted afterwards.
1359 // 'selrawdata' flag can be used to enable writing of detectors raw data
1360 // accoring to the trigger cluster.
1361
1362   AliCodeTimerAuto("",0)
1363   AliSysInfo::AddStamp("WriteRawData_Start");
1364   
1365   TString detStr = detectors;
1366   if (!WriteRawFiles(detStr.Data())) {
1367     if (fStopOnError) return kFALSE;
1368   }
1369   AliSysInfo::AddStamp("WriteRawFiles");
1370
1371   // run HLT simulation on simulated DDL raw files
1372   // and produce HLT ddl raw files to be included in date/root file
1373   // bugfix 2009-06-26: the decision whether to write HLT raw data
1374   // is taken in RunHLT. Here HLT always needs to be run in order to
1375   // create HLT digits, unless its switched off. This is due to the
1376   // special placement of the HLT between the generation of DDL files
1377   // and conversion to DATE/Root file.
1378   detStr.ReplaceAll("HLT", "");
1379   if (!fRunHLT.IsNull()) {
1380     if (!RunHLT()) {
1381       if (fStopOnError) return kFALSE;
1382     }
1383   }
1384   AliSysInfo::AddStamp("WriteRawData_RunHLT");
1385
1386   TString dateFileName(fileName);
1387   if (!dateFileName.IsNull()) {
1388     Bool_t rootOutput = dateFileName.EndsWith(".root");
1389     if (rootOutput) dateFileName += ".date";
1390     TString selDateFileName;
1391     if (selrawdata) {
1392       selDateFileName = "selected.";
1393       selDateFileName+= dateFileName;
1394     }
1395     if (!ConvertRawFilesToDate(dateFileName,selDateFileName)) {
1396       if (fStopOnError) return kFALSE;
1397     }
1398     AliSysInfo::AddStamp("ConvertRawFilesToDate");
1399     if (deleteIntermediateFiles) {
1400       AliRunLoader* runLoader = LoadRun("READ");
1401       if (runLoader) for (Int_t iEvent = 0; 
1402                           iEvent < runLoader->GetNumberOfEvents(); iEvent++) {
1403         char command[256];
1404         snprintf(command, 256, "rm -r raw%d", iEvent);
1405         gSystem->Exec(command);
1406       }
1407       delete runLoader;
1408     }
1409
1410     if (rootOutput) {
1411       if (!ConvertDateToRoot(dateFileName, fileName)) {
1412         if (fStopOnError) return kFALSE;
1413       }
1414       AliSysInfo::AddStamp("ConvertDateToRoot");
1415       if (deleteIntermediateFiles) {
1416         gSystem->Unlink(dateFileName);
1417       }
1418       if (selrawdata) {
1419         TString selFileName = "selected.";
1420         selFileName        += fileName;
1421         if (!ConvertDateToRoot(selDateFileName, selFileName)) {
1422           if (fStopOnError) return kFALSE;
1423         }
1424         if (deleteIntermediateFiles) {
1425           gSystem->Unlink(selDateFileName);
1426         }
1427       }
1428     }
1429   }
1430
1431   return kTRUE;
1432 }
1433
1434 //_____________________________________________________________________________
1435 Bool_t AliSimulation::WriteRawFiles(const char* detectors)
1436 {
1437 // convert the digits to raw data DDL files
1438
1439   AliCodeTimerAuto("",0)
1440   
1441   AliRunLoader* runLoader = LoadRun("READ");
1442   if (!runLoader) return kFALSE;
1443
1444   // write raw data to DDL files
1445   for (Int_t iEvent = 0; iEvent < runLoader->GetNumberOfEvents(); iEvent++) {
1446     AliInfo(Form("processing event %d", iEvent));
1447     runLoader->GetEvent(iEvent);
1448     TString baseDir = gSystem->WorkingDirectory();
1449     char dirName[256];
1450     snprintf(dirName, 256, "raw%d", iEvent);
1451     gSystem->MakeDirectory(dirName);
1452     if (!gSystem->ChangeDirectory(dirName)) {
1453       AliError(Form("couldn't change to directory %s", dirName));
1454       if (fStopOnError) return kFALSE; else continue;
1455     }
1456
1457     ofstream runNbFile(Form("run%u",runLoader->GetHeader()->GetRun()));
1458     runNbFile.close();
1459
1460     TString detStr = detectors;
1461     if (IsSelected("HLT", detStr)) {
1462       // Do nothing. "HLT" will be removed from detStr and HLT raw
1463       // data files are generated in RunHLT.
1464     }
1465
1466     TObjArray* detArray = runLoader->GetAliRun()->Detectors();
1467     for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
1468       AliModule* det = (AliModule*) detArray->At(iDet);
1469       if (!det || !det->IsActive()) continue;
1470       if (IsSelected(det->GetName(), detStr)) {
1471         AliInfo(Form("creating raw data from digits for %s", det->GetName()));
1472         det->Digits2Raw();
1473       }
1474     }
1475
1476     if (!WriteTriggerRawData())
1477       if (fStopOnError) return kFALSE;
1478
1479     gSystem->ChangeDirectory(baseDir);
1480     if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
1481       AliError(Form("the following detectors were not found: %s", 
1482                     detStr.Data()));
1483       if (fStopOnError) return kFALSE;
1484     }
1485   }
1486
1487   delete runLoader;
1488   
1489   return kTRUE;
1490 }
1491
1492 //_____________________________________________________________________________
1493 Bool_t AliSimulation::ConvertRawFilesToDate(const char* dateFileName,
1494                                             const char* selDateFileName)
1495 {
1496 // convert raw data DDL files to a DATE file with the program "dateStream"
1497 // The second argument is not empty when the user decides to write
1498 // the detectors raw data according to the trigger cluster.
1499
1500   AliCodeTimerAuto("",0)
1501   
1502   char* path = gSystem->Which(gSystem->Getenv("PATH"), "dateStream");
1503   if (!path) {
1504     AliError("the program dateStream was not found");
1505     if (fStopOnError) return kFALSE;
1506   } else {
1507     delete[] path;
1508   }
1509
1510   AliRunLoader* runLoader = LoadRun("READ");
1511   if (!runLoader) return kFALSE;
1512
1513   AliInfo(Form("converting raw data DDL files to DATE file %s", dateFileName));
1514   Bool_t selrawdata = kFALSE;
1515   if (strcmp(selDateFileName,"") != 0) selrawdata = kTRUE;
1516
1517   char command[256];
1518   // Note the option -s. It is used in order to avoid
1519   // the generation of SOR/EOR events.
1520   snprintf(command, 256, "dateStream -c -s -D -o %s -# %d -C -run %d", 
1521           dateFileName, runLoader->GetNumberOfEvents(),runLoader->GetHeader()->GetRun());
1522   FILE* pipe = gSystem->OpenPipe(command, "w");
1523
1524   if (!pipe) {
1525     AliError(Form("Cannot execute command: %s",command));
1526     return kFALSE;
1527   }
1528
1529   Int_t selEvents = 0;
1530   for (Int_t iEvent = 0; iEvent < runLoader->GetNumberOfEvents(); iEvent++) {
1531
1532     UInt_t detectorPattern = 0;
1533     runLoader->GetEvent(iEvent);
1534     if (!runLoader->LoadTrigger()) {
1535       AliCentralTrigger *aCTP = runLoader->GetTrigger();
1536       detectorPattern = aCTP->GetClusterMask();
1537       // Check if the event was triggered by CTP
1538       if (selrawdata) {
1539         if (aCTP->GetClassMask()) selEvents++;
1540       }
1541     }
1542     else {
1543       AliWarning("No trigger can be loaded! Some fields in the event header will be empty !");
1544       if (selrawdata) {
1545         AliWarning("No trigger can be loaded! Writing of selected raw data is abandoned !");
1546         selrawdata = kFALSE;
1547       }
1548     }
1549
1550     fprintf(pipe, "GDC DetectorPattern %u\n", detectorPattern);
1551     Float_t ldc = 0;
1552     Int_t prevLDC = -1;
1553
1554     // loop over detectors and DDLs
1555     for (Int_t iDet = 0; iDet < AliDAQ::kNDetectors; iDet++) {
1556       for (Int_t iDDL = 0; iDDL < AliDAQ::NumberOfDdls(iDet); iDDL++) {
1557
1558         Int_t ddlID = AliDAQ::DdlID(iDet,iDDL);
1559         Int_t ldcID = Int_t(ldc + 0.0001);
1560         ldc += AliDAQ::NumberOfLdcs(iDet) / AliDAQ::NumberOfDdls(iDet);
1561
1562         char rawFileName[256];
1563         snprintf(rawFileName, 256, "raw%d/%s", 
1564                 iEvent, AliDAQ::DdlFileName(iDet,iDDL));
1565
1566         // check existence and size of raw data file
1567         FILE* file = fopen(rawFileName, "rb");
1568         if (!file) continue;
1569         fseek(file, 0, SEEK_END);
1570         unsigned long size = ftell(file);
1571         fclose(file);
1572         if (!size) continue;
1573
1574         if (ldcID != prevLDC) {
1575           fprintf(pipe, " LDC Id %d\n", ldcID);
1576           prevLDC = ldcID;
1577         }
1578         fprintf(pipe, "  Equipment Id %d Payload %s\n", ddlID, rawFileName);
1579       }
1580     }
1581   }
1582
1583   Int_t result = gSystem->ClosePipe(pipe);
1584
1585   if (!(selrawdata && selEvents > 0)) {
1586     delete runLoader;
1587     return (result == 0);
1588   }
1589
1590   AliInfo(Form("converting selected by trigger cluster raw data DDL files to DATE file %s", selDateFileName));
1591   
1592   snprintf(command, 256, "dateStream -c -s -D -o %s -# %d -C -run %d", 
1593           selDateFileName,selEvents,runLoader->GetHeader()->GetRun());
1594   FILE* pipe2 = gSystem->OpenPipe(command, "w");
1595
1596   for (Int_t iEvent = 0; iEvent < runLoader->GetNumberOfEvents(); iEvent++) {
1597
1598     // Get the trigger decision and cluster
1599     UInt_t detectorPattern = 0;
1600     TString detClust;
1601     runLoader->GetEvent(iEvent);
1602     if (!runLoader->LoadTrigger()) {
1603       AliCentralTrigger *aCTP = runLoader->GetTrigger();
1604       if (aCTP->GetClassMask() == 0) continue;
1605       detectorPattern = aCTP->GetClusterMask();
1606       detClust = AliDAQ::ListOfTriggeredDetectors(detectorPattern);
1607       AliInfo(Form("List of detectors to be read out: %s",detClust.Data()));
1608     }
1609
1610     fprintf(pipe2, "GDC DetectorPattern %u\n", detectorPattern);
1611     Float_t ldc = 0;
1612     Int_t prevLDC = -1;
1613
1614     // loop over detectors and DDLs
1615     for (Int_t iDet = 0; iDet < AliDAQ::kNDetectors; iDet++) {
1616       // Write only raw data from detectors that
1617       // are contained in the trigger cluster(s)
1618       if (!IsSelected(AliDAQ::DetectorName(iDet),detClust)) continue;
1619
1620       for (Int_t iDDL = 0; iDDL < AliDAQ::NumberOfDdls(iDet); iDDL++) {
1621
1622         Int_t ddlID = AliDAQ::DdlID(iDet,iDDL);
1623         Int_t ldcID = Int_t(ldc + 0.0001);
1624         ldc += AliDAQ::NumberOfLdcs(iDet) / AliDAQ::NumberOfDdls(iDet);
1625
1626         char rawFileName[256];
1627         snprintf(rawFileName, 256, "raw%d/%s", 
1628                 iEvent, AliDAQ::DdlFileName(iDet,iDDL));
1629
1630         // check existence and size of raw data file
1631         FILE* file = fopen(rawFileName, "rb");
1632         if (!file) continue;
1633         fseek(file, 0, SEEK_END);
1634         unsigned long size = ftell(file);
1635         fclose(file);
1636         if (!size) continue;
1637
1638         if (ldcID != prevLDC) {
1639           fprintf(pipe2, " LDC Id %d\n", ldcID);
1640           prevLDC = ldcID;
1641         }
1642         fprintf(pipe2, "  Equipment Id %d Payload %s\n", ddlID, rawFileName);
1643       }
1644     }
1645   }
1646
1647   Int_t result2 = gSystem->ClosePipe(pipe2);
1648
1649   delete runLoader;
1650   return ((result == 0) && (result2 == 0));
1651 }
1652
1653 //_____________________________________________________________________________
1654 Bool_t AliSimulation::ConvertDateToRoot(const char* dateFileName,
1655                                         const char* rootFileName)
1656 {
1657 // convert a DATE file to a root file with the program "alimdc"
1658
1659   // ALIMDC setup
1660   const Int_t kDBSize = 2000000000;
1661   const Int_t kTagDBSize = 1000000000;
1662   const Bool_t kFilter = kFALSE;
1663   const Int_t kCompression = 1;
1664
1665   char* path = gSystem->Which(gSystem->Getenv("PATH"), "alimdc");
1666   if (!path) {
1667     AliError("the program alimdc was not found");
1668     if (fStopOnError) return kFALSE;
1669   } else {
1670     delete[] path;
1671   }
1672
1673   AliInfo(Form("converting DATE file %s to root file %s", 
1674                dateFileName, rootFileName));
1675
1676   const char* rawDBFS[2] = { "/tmp/mdc1", "/tmp/mdc2" };
1677   const char* tagDBFS    = "/tmp/mdc1/tags";
1678
1679   // User defined file system locations
1680   if (gSystem->Getenv("ALIMDC_RAWDB1")) 
1681     rawDBFS[0] = gSystem->Getenv("ALIMDC_RAWDB1");
1682   if (gSystem->Getenv("ALIMDC_RAWDB2")) 
1683     rawDBFS[1] = gSystem->Getenv("ALIMDC_RAWDB2");
1684   if (gSystem->Getenv("ALIMDC_TAGDB")) 
1685     tagDBFS = gSystem->Getenv("ALIMDC_TAGDB");
1686
1687   gSystem->Exec(Form("rm -rf %s",rawDBFS[0]));
1688   gSystem->Exec(Form("rm -rf %s",rawDBFS[1]));
1689   gSystem->Exec(Form("rm -rf %s",tagDBFS));
1690
1691   gSystem->Exec(Form("mkdir %s",rawDBFS[0]));
1692   gSystem->Exec(Form("mkdir %s",rawDBFS[1]));
1693   gSystem->Exec(Form("mkdir %s",tagDBFS));
1694
1695   Int_t result = gSystem->Exec(Form("alimdc %d %d %d %d %s", 
1696                                     kDBSize, kTagDBSize, kFilter, kCompression, dateFileName));
1697   gSystem->Exec(Form("mv %s/*.root %s", rawDBFS[0], rootFileName));
1698
1699   gSystem->Exec(Form("rm -rf %s",rawDBFS[0]));
1700   gSystem->Exec(Form("rm -rf %s",rawDBFS[1]));
1701   gSystem->Exec(Form("rm -rf %s",tagDBFS));
1702
1703   return (result == 0);
1704 }
1705
1706
1707 //_____________________________________________________________________________
1708 AliRunLoader* AliSimulation::LoadRun(const char* mode) const
1709 {
1710 // delete existing run loaders, open a new one and load gAlice
1711
1712   delete AliRunLoader::Instance();
1713   AliRunLoader* runLoader = 
1714     AliRunLoader::Open(fGAliceFileName.Data(), 
1715                        AliConfig::GetDefaultEventFolderName(), mode);
1716   if (!runLoader) {
1717     AliError(Form("no run loader found in file %s", fGAliceFileName.Data()));
1718     return NULL;
1719   }
1720   runLoader->LoadgAlice();
1721   runLoader->LoadHeader();
1722   gAlice = runLoader->GetAliRun();
1723   if (!gAlice) {
1724     AliError(Form("no gAlice object found in file %s", 
1725                   fGAliceFileName.Data()));
1726     return NULL;
1727   }
1728   return runLoader;
1729 }
1730
1731 //_____________________________________________________________________________
1732 Int_t AliSimulation::GetNSignalPerBkgrd(Int_t nEvents) const
1733 {
1734 // get or calculate the number of signal events per background event
1735
1736   if (!fBkgrdFileNames) return 1;
1737   Int_t nBkgrdFiles = fBkgrdFileNames->GetEntriesFast();
1738   if (nBkgrdFiles == 0) return 1;
1739
1740   // get the number of signal events
1741   if (nEvents <= 0) {
1742     AliRunLoader* runLoader = 
1743         AliRunLoader::Open(fGAliceFileName.Data(), "SIGNAL");
1744     if (!runLoader) return 1;
1745     
1746     nEvents = runLoader->GetNumberOfEvents();
1747     delete runLoader;
1748   }
1749
1750   Int_t result = 0;
1751   for (Int_t iBkgrdFile = 0; iBkgrdFile < nBkgrdFiles; iBkgrdFile++) {
1752     // get the number of background events
1753     const char* fileName = ((TObjString*)
1754                             (fBkgrdFileNames->At(iBkgrdFile)))->GetName();
1755     AliRunLoader* runLoader =
1756       AliRunLoader::Open(fileName, "BKGRD");
1757     if (!runLoader) continue;
1758     Int_t nBkgrdEvents = runLoader->GetNumberOfEvents();
1759     delete runLoader;
1760   
1761     // get or calculate the number of signal per background events
1762     Int_t nSignalPerBkgrd = fBkgrdFileNames->At(iBkgrdFile)->GetUniqueID();
1763     if (nSignalPerBkgrd <= 0) {
1764       nSignalPerBkgrd = (nEvents-1) / nBkgrdEvents + 1;
1765     } else if (result && (result != nSignalPerBkgrd)) {
1766       AliInfo(Form("the number of signal events per background event "
1767                    "will be changed from %d to %d for stream %d", 
1768                    nSignalPerBkgrd, result, iBkgrdFile+1));
1769       nSignalPerBkgrd = result;
1770     }
1771
1772     if (!result) result = nSignalPerBkgrd;
1773     if (nSignalPerBkgrd * nBkgrdEvents < nEvents) {
1774       AliWarning(Form("not enough background events (%d) for %d signal events "
1775                       "using %d signal per background events for stream %d",
1776                       nBkgrdEvents, nEvents, nSignalPerBkgrd, iBkgrdFile+1));
1777     }
1778   }
1779
1780   return result;
1781 }
1782
1783 //_____________________________________________________________________________
1784 Bool_t AliSimulation::IsSelected(TString detName, TString& detectors) const
1785 {
1786 // check whether detName is contained in detectors
1787 // if yes, it is removed from detectors
1788
1789   // check if all detectors are selected
1790   if ((detectors.CompareTo("ALL") == 0) ||
1791       detectors.BeginsWith("ALL ") ||
1792       detectors.EndsWith(" ALL") ||
1793       detectors.Contains(" ALL ")) {
1794     detectors = "ALL";
1795     return kTRUE;
1796   }
1797
1798   // search for the given detector
1799   Bool_t result = kFALSE;
1800   if ((detectors.CompareTo(detName) == 0) ||
1801       detectors.BeginsWith(detName+" ") ||
1802       detectors.EndsWith(" "+detName) ||
1803       detectors.Contains(" "+detName+" ")) {
1804     detectors.ReplaceAll(detName, "");
1805     result = kTRUE;
1806   }
1807
1808   // clean up the detectors string
1809   while (detectors.Contains("  ")) detectors.ReplaceAll("  ", " ");
1810   while (detectors.BeginsWith(" ")) detectors.Remove(0, 1);
1811   while (detectors.EndsWith(" ")) detectors.Remove(detectors.Length()-1, 1);
1812
1813   return result;
1814 }
1815
1816 //_____________________________________________________________________________
1817 Bool_t AliSimulation::ConvertRaw2SDigits(const char* rawDirectory, const char* esdFileName, Int_t N) 
1818 {
1819 //
1820 // Steering routine  to convert raw data in directory rawDirectory/ to fake SDigits. 
1821 // These can be used for embedding of MC tracks into RAW data using the standard 
1822 // merging procedure.
1823 //
1824 // If an ESD file is given the reconstructed vertex is taken from it and stored in the event header.
1825 //
1826   if (!gAlice) {
1827     AliError("no gAlice object. Restart aliroot and try again.");
1828     return kFALSE;
1829   }
1830   if (gAlice->Modules()->GetEntries() > 0) {
1831     AliError("gAlice was already run. Restart aliroot and try again.");
1832     return kFALSE;
1833   }
1834   
1835   AliInfo(Form("initializing gAlice with config file %s",fConfigFileName.Data()));
1836   
1837   gAlice->Announce();
1838   
1839   gROOT->LoadMacro(fConfigFileName.Data());
1840   gInterpreter->ProcessLine(gAlice->GetConfigFunction());
1841   
1842   if(AliCDBManager::Instance()->GetRun() >= 0) { 
1843         SetRunNumber(AliCDBManager::Instance()->GetRun());
1844   } else {
1845         AliWarning("Run number not initialized!!");
1846   }
1847   
1848    AliRunLoader::Instance()->CdGAFile();
1849     
1850    AliPDG::AddParticlesToPdgDataBase();  
1851
1852    gMC->SetMagField(TGeoGlobalMagField::Instance()->GetField());
1853    
1854    gAlice->GetMCApp()->Init();
1855
1856    //Must be here because some MCs (G4) adds detectors here and not in Config.C
1857    gAlice->InitLoaders();
1858    AliRunLoader::Instance()->MakeTree("E");
1859    AliRunLoader::Instance()->LoadKinematics("RECREATE");
1860    AliRunLoader::Instance()->LoadTrackRefs("RECREATE");
1861    AliRunLoader::Instance()->LoadHits("all","RECREATE");
1862
1863    //
1864    // Save stuff at the beginning of the file to avoid file corruption
1865    AliRunLoader::Instance()->CdGAFile();
1866    gAlice->Write();
1867 //
1868 //  Initialize CDB     
1869     InitCDB();
1870     //AliCDBManager* man = AliCDBManager::Instance();
1871     //man->SetRun(0); // Should this come from rawdata header ?
1872     
1873     Int_t iDet;
1874     //
1875     // Get the runloader
1876     AliRunLoader* runLoader = AliRunLoader::Instance();
1877     //
1878     // Open esd file if available
1879     TFile* esdFile = 0;
1880     TTree* treeESD = 0;
1881     AliESDEvent* esd = 0;
1882     if (esdFileName && (strlen(esdFileName)>0)) {
1883       esdFile = TFile::Open(esdFileName);
1884       if (esdFile) {
1885         esd = new AliESDEvent();
1886         esdFile->GetObject("esdTree", treeESD);
1887         if (treeESD) esd->ReadFromTree(treeESD);
1888       }
1889     }
1890
1891     //
1892     // Create the RawReader
1893     TString fileName(rawDirectory);
1894     AliRawReader* rawReader = 0x0;
1895     if (fileName.EndsWith("/")) {
1896       rawReader = new AliRawReaderFile(fileName);
1897     } else if (fileName.EndsWith(".root")) {
1898       rawReader = new AliRawReaderRoot(fileName);
1899     } else if (!fileName.IsNull()) {
1900       rawReader = new AliRawReaderDate(fileName);
1901     }
1902     if (!rawReader) return (kFALSE);
1903     
1904 //     if (!fEquipIdMap.IsNull() && fRawReader)
1905 //       fRawReader->LoadEquipmentIdsMap(fEquipIdMap);
1906     //
1907     // Get list of detectors
1908     TObjArray* detArray = runLoader->GetAliRun()->Detectors();
1909     //
1910     // Get Header
1911     AliHeader* header = runLoader->GetHeader();
1912     // Event loop
1913     Int_t nev = 0;
1914     while(kTRUE) {
1915         if (!(rawReader->NextEvent())) break;
1916         runLoader->SetEventNumber(nev);
1917         runLoader->GetHeader()->Reset(rawReader->GetRunNumber(), 
1918                                       nev, nev);
1919         runLoader->GetEvent(nev);
1920         AliInfo(Form("We are at event %d",nev));
1921         //
1922         // Detector loop
1923         TString detStr = fMakeSDigits;
1924         for (iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
1925             AliModule* det = (AliModule*) detArray->At(iDet);
1926             if (!det || !det->IsActive()) continue;
1927             if (IsSelected(det->GetName(), detStr)) {
1928               AliInfo(Form("Calling Raw2SDigits for %s", det->GetName()));
1929               det->Raw2SDigits(rawReader);
1930               rawReader->Reset();
1931             }
1932         } // detectors
1933         
1934
1935         //
1936         //  If ESD information available obtain reconstructed vertex and store in header.
1937         if (treeESD) {
1938             treeESD->GetEvent(nev);
1939             const AliESDVertex* esdVertex = esd->GetPrimaryVertex();
1940             Double_t position[3];
1941             esdVertex->GetXYZ(position);
1942             AliGenEventHeader* mcHeader = new  AliGenEventHeader("ESD");
1943             TArrayF mcV;
1944             mcV.Set(3);
1945             for (Int_t i = 0; i < 3; i++) mcV[i] = position[i];
1946             mcHeader->SetPrimaryVertex(mcV);
1947             header->Reset(0,nev);
1948             header->SetGenEventHeader(mcHeader);
1949             AliInfo(Form("***** Saved vertex %f %f %f \n", position[0], position[1], position[2]));
1950         }
1951 //
1952 //      Finish the event
1953         runLoader->TreeE()->Fill();
1954         AliInfo(Form("Finished event %d",nev));
1955         nev++;
1956         if (N>0&&nev>=N)
1957           break;
1958     } // events
1959  
1960     delete rawReader;
1961 //
1962 //  Finish the run 
1963     runLoader->CdGAFile();
1964     runLoader->WriteHeader("OVERWRITE");
1965     runLoader->WriteRunLoader();
1966
1967     return kTRUE;
1968 }
1969
1970 //_____________________________________________________________________________
1971 void AliSimulation::FinishRun()
1972 {
1973   //
1974   // Called at the end of the run.
1975   //
1976
1977   if(IsLegoRun()) 
1978    {
1979     AliDebug(1, "Finish Lego");
1980     AliRunLoader::Instance()->CdGAFile();
1981     fLego->FinishRun();
1982    }
1983   
1984   // Clean detector information
1985   TIter next(gAlice->Modules());
1986   AliModule *detector;
1987   while((detector = dynamic_cast<AliModule*>(next()))) {
1988     AliDebug(2, Form("%s->FinishRun()", detector->GetName()));
1989     detector->FinishRun();
1990   }
1991   
1992   AliDebug(1, "AliRunLoader::Instance()->WriteHeader(OVERWRITE)");
1993   AliRunLoader::Instance()->WriteHeader("OVERWRITE");
1994
1995   // Write AliRun info and all detectors parameters
1996   AliRunLoader::Instance()->CdGAFile();
1997   gAlice->Write(0,TObject::kOverwrite);//write AliRun
1998   AliRunLoader::Instance()->Write(0,TObject::kOverwrite);//write RunLoader itself
1999   
2000   if(gAlice->GetMCApp()) gAlice->GetMCApp()->FinishRun();  
2001   AliRunLoader::Instance()->Synchronize();
2002 }
2003
2004 //_____________________________________________________________________________
2005 Int_t AliSimulation::GetDetIndex(const char* detector)
2006 {
2007   // return the detector index corresponding to detector
2008   Int_t index = -1 ; 
2009   for (index = 0; index < fgkNDetectors ; index++) {
2010     if ( strcmp(detector, fgkDetectorName[index]) == 0 )
2011           break ; 
2012   }     
2013   return index ; 
2014 }
2015
2016 //_____________________________________________________________________________
2017 Bool_t AliSimulation::CreateHLT()
2018 {
2019   // Init the HLT simulation.
2020   // The function  loads the library and creates the instance of AliHLTSimulation.
2021   // the main reason for the decoupled creation is to set the transient OCDB
2022   // objects before the OCDB is locked
2023
2024   // load the library dynamically
2025   gSystem->Load(ALIHLTSIMULATION_LIBRARY);
2026
2027   // check for the library version
2028   AliHLTSimulationGetLibraryVersion_t fctVersion=(AliHLTSimulationGetLibraryVersion_t)(gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_GET_LIBRARY_VERSION));
2029   if (!fctVersion) {
2030     AliError(Form("can not load library %s", ALIHLTSIMULATION_LIBRARY));
2031     return kFALSE;
2032   }
2033   if (fctVersion()!= ALIHLTSIMULATION_LIBRARY_VERSION) {
2034     AliWarning(Form("%s version does not match: compiled for version %d, loaded %d", ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_LIBRARY_VERSION, fctVersion()));
2035   }
2036
2037   // print compile info
2038   typedef void (*CompileInfo)( const char*& date, const char*& time);
2039   CompileInfo fctInfo=(CompileInfo)gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, "CompileInfo");
2040   if (fctInfo) {
2041     const char* date="";
2042     const char* time="";
2043     (*fctInfo)(date, time);
2044     if (!date) date="unknown";
2045     if (!time) time="unknown";
2046     AliInfo(Form("%s build on %s (%s)", ALIHLTSIMULATION_LIBRARY, date, time));
2047   } else {
2048     AliInfo(Form("no build info available for %s", ALIHLTSIMULATION_LIBRARY));
2049   }
2050
2051   // create instance of the HLT simulation
2052   AliHLTSimulationCreateInstance_t fctCreate=(AliHLTSimulationCreateInstance_t)(gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_CREATE_INSTANCE));
2053   if (fctCreate==NULL || (fpHLT=(fctCreate()))==NULL) {
2054     AliError(Form("can not create instance of HLT simulation (creator %p)", fctCreate));
2055     return kFALSE;    
2056   }
2057
2058   TString specObjects;
2059   for (Int_t i = 0; i < fSpecCDBUri.GetEntriesFast(); i++) {
2060     if (specObjects.Length()>0) specObjects+=" ";
2061     specObjects+=fSpecCDBUri[i]->GetName();
2062   }
2063
2064   AliHLTSimulationSetup_t fctSetup=(AliHLTSimulationSetup_t)(gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_SETUP));
2065   if (fctSetup==NULL || fctSetup(fpHLT, this, specObjects.Data())<0) {
2066     AliWarning(Form("failed to setup HLT simulation (function %p)", fctSetup));
2067   }
2068
2069   return kTRUE;
2070 }
2071
2072 //_____________________________________________________________________________
2073 Bool_t AliSimulation::RunHLT()
2074 {
2075   // Run the HLT simulation
2076   // HLT simulation is implemented in HLT/sim/AliHLTSimulation
2077   // Disabled if fRunHLT is empty, default vaule is "default".
2078   // AliSimulation::SetRunHLT can be used to set the options for HLT simulation
2079   // The default simulation depends on the HLT component libraries and their
2080   // corresponding agents which define components and chains to run. See
2081   // http://web.ift.uib.no/~kjeks/doc/alice-hlt-current/
2082   // http://web.ift.uib.no/~kjeks/doc/alice-hlt-current/classAliHLTModuleAgent.html
2083   //
2084   // The libraries to be loaded can be specified as an option.
2085   // <pre>
2086   // AliSimulation sim;
2087   // sim.SetRunHLT("libAliHLTSample.so");
2088   // </pre>
2089   // will only load <tt>libAliHLTSample.so</tt>
2090
2091   // Other available options:
2092   // \li loglevel=<i>level</i> <br>
2093   //     logging level for this processing
2094   // \li alilog=off
2095   //     disable redirection of log messages to AliLog class
2096   // \li config=<i>macro</i>
2097   //     configuration macro
2098   // \li chains=<i>configuration</i>
2099   //     comma separated list of configurations to be run during simulation
2100   // \li rawfile=<i>file</i>
2101   //     source for the RawReader to be created, the default is <i>./</i> if
2102   //     raw data is simulated
2103
2104   int iResult=0;
2105
2106   if (!fpHLT && !CreateHLT()) {
2107     return kFALSE;
2108   }
2109   AliHLTSimulation* pHLT=fpHLT;
2110
2111   AliRunLoader* pRunLoader = LoadRun("READ");
2112   if (!pRunLoader) return kFALSE;
2113
2114   // initialize CDB storage, run number, set CDB lock
2115   // thats for the case of running HLT simulation without all the other steps
2116   // multiple calls are handled by the function, so we can just call
2117   InitCDB();
2118   if (!SetRunNumberFromData()) if (fStopOnError) return kFALSE;
2119   SetCDBLock();
2120   
2121   // init the HLT simulation
2122   TString options;
2123   if (fRunHLT.CompareTo("default")!=0) options=fRunHLT;
2124   TString detStr = fWriteRawData;
2125   if (!IsSelected("HLT", detStr)) {
2126     options+=" writerawfiles=";
2127   } else {
2128     options+=" writerawfiles=HLT";
2129   }
2130
2131   if (!detStr.IsNull() && !options.Contains("rawfile=")) {
2132     // as a matter of fact, HLT will run reconstruction and needs the RawReader
2133     // in order to get detector data. By default, RawReaderFile is used to read
2134     // the already simulated ddl files. Date and Root files from the raw data
2135     // are generated after the HLT simulation.
2136     options+=" rawfile=./";
2137   }
2138
2139   AliHLTSimulationInit_t fctInit=(AliHLTSimulationInit_t)(gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_INIT));
2140   if (fctInit==NULL || (iResult=(fctInit(pHLT, pRunLoader, options.Data())))<0) {
2141     AliError(Form("can not init HLT simulation: error %d (init %p)", iResult, fctInit));
2142   } else {
2143     // run the HLT simulation
2144     AliHLTSimulationRun_t fctRun=(AliHLTSimulationRun_t)(gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_RUN));
2145     if (fctRun==NULL || (iResult=(fctRun(pHLT, pRunLoader)))<0) {
2146       AliError(Form("can not run HLT simulation: error %d (run %p)", iResult, fctRun));
2147     }
2148   }
2149
2150   // delete the instance
2151   AliHLTSimulationDeleteInstance_t fctDelete=(AliHLTSimulationDeleteInstance_t)(gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_DELETE_INSTANCE));
2152   if (fctDelete==NULL || fctDelete(pHLT)<0) {
2153     AliError(Form("can not delete instance of HLT simulation (creator %p)", fctDelete));
2154   }
2155   pHLT=NULL;
2156
2157   return iResult>=0?kTRUE:kFALSE;
2158 }
2159
2160 //_____________________________________________________________________________
2161 Bool_t AliSimulation::RunQA()
2162 {
2163         // run the QA on summable hits, digits or digits
2164         
2165     //if(!gAlice) return kFALSE;
2166         AliQAManager::QAManager()->SetRunLoader(AliRunLoader::Instance()) ;
2167
2168         TString detectorsw("") ;  
2169         Bool_t rv = kTRUE ; 
2170   AliQAManager::QAManager()->SetEventSpecie(fEventSpecie) ;
2171         detectorsw = AliQAManager::QAManager()->Run(fQADetectors.Data()) ; 
2172         if ( detectorsw.IsNull() ) 
2173                 rv = kFALSE ; 
2174         return rv ; 
2175 }
2176
2177 //_____________________________________________________________________________
2178 Bool_t AliSimulation::SetRunQA(TString detAndAction) 
2179 {
2180         // Allows to run QA for a selected set of detectors
2181         // and a selected set of tasks among HITS, SDIGITS and DIGITS
2182         // all selected detectors run the same selected tasks
2183         
2184         if (!detAndAction.Contains(":")) {
2185                 AliError( Form("%s is a wrong syntax, use \"DetectorList:ActionList\" \n", detAndAction.Data()) ) ;
2186                 fRunQA = kFALSE ;
2187                 return kFALSE ;                 
2188         }
2189         Int_t colon = detAndAction.Index(":") ; 
2190         fQADetectors = detAndAction(0, colon) ; 
2191         if (fQADetectors.Contains("ALL") ){
2192     TString tmp = Form("%s %s", fMakeDigits.Data(), fMakeDigitsFromHits.Data()) ; 
2193     Int_t minus = fQADetectors.Last('-') ; 
2194     TString toKeep = Form("%s %s", fMakeDigits.Data(), fMakeDigitsFromHits.Data()) ; 
2195     TString toRemove("") ;
2196     while (minus >= 0) {
2197       toRemove = fQADetectors(minus+1, fQADetectors.Length()) ; 
2198       toRemove = toRemove.Strip() ; 
2199       toKeep.ReplaceAll(toRemove, "") ; 
2200       fQADetectors.ReplaceAll(Form("-%s", toRemove.Data()), "") ; 
2201       minus = fQADetectors.Last('-') ; 
2202     }
2203     fQADetectors = toKeep ; 
2204   }
2205   fQATasks   = detAndAction(colon+1, detAndAction.Sizeof() ) ; 
2206         if (fQATasks.Contains("ALL") ) {
2207                 fQATasks = Form("%d %d %d", AliQAv1::kHITS, AliQAv1::kSDIGITS, AliQAv1::kDIGITS) ; 
2208         } else {
2209                 fQATasks.ToUpper() ; 
2210                 TString tempo("") ; 
2211                 if ( fQATasks.Contains("HIT") ) 
2212                         tempo = Form("%d ", AliQAv1::kHITS) ; 
2213                 if ( fQATasks.Contains("SDIGIT") ) 
2214                         tempo += Form("%d ", AliQAv1::kSDIGITS) ; 
2215                 if ( fQATasks.Contains("DIGIT") ) 
2216                         tempo += Form("%d ", AliQAv1::kDIGITS) ; 
2217                 fQATasks = tempo ; 
2218                 if (fQATasks.IsNull()) {
2219                         AliInfo("No QA requested\n")  ;
2220                         fRunQA = kFALSE ;
2221                         return kTRUE ; 
2222                 }
2223         }       
2224         TString tempo(fQATasks) ; 
2225     tempo.ReplaceAll(Form("%d", AliQAv1::kHITS), AliQAv1::GetTaskName(AliQAv1::kHITS))  ;
2226     tempo.ReplaceAll(Form("%d", AliQAv1::kSDIGITS), AliQAv1::GetTaskName(AliQAv1::kSDIGITS)) ;  
2227     tempo.ReplaceAll(Form("%d", AliQAv1::kDIGITS), AliQAv1::GetTaskName(AliQAv1::kDIGITS)) ;    
2228         AliInfo( Form("QA will be done on \"%s\" for \"%s\"\n", fQADetectors.Data(), tempo.Data()) ) ;  
2229         fRunQA = kTRUE ;
2230         AliQAManager::QAManager()->SetActiveDetectors(fQADetectors) ; 
2231         AliQAManager::QAManager()->SetTasks(fQATasks) ; 
2232   for (Int_t det = 0 ; det < AliQAv1::kNDET ; det++) 
2233     AliQAManager::QAManager()->SetWriteExpert(AliQAv1::DETECTORINDEX_t(det)) ;
2234   
2235         return kTRUE; 
2236
2237
2238 //_____________________________________________________________________________
2239 void AliSimulation::ProcessEnvironmentVars()
2240 {
2241 // Extract run number and random generator seed from env variables
2242
2243     AliInfo("Processing environment variables");
2244     
2245     // Random Number seed
2246     
2247     // first check that seed is not already set
2248     if (fSeed == 0) {
2249         if (gSystem->Getenv("CONFIG_SEED")) {
2250                 fSeed = atoi(gSystem->Getenv("CONFIG_SEED"));
2251         }
2252     } else {
2253         if (gSystem->Getenv("CONFIG_SEED")) {
2254                 AliInfo(Form("Seed for random number generation already set (%d)"
2255                              ": CONFIG_SEED variable ignored!", fSeed));
2256         }
2257     }
2258    
2259     AliInfo(Form("Seed for random number generation = %d ", fSeed)); 
2260
2261     // Run Number
2262     
2263     // first check that run number is not already set
2264     if(fRun < 0) {    
2265         if (gSystem->Getenv("DC_RUN")) {
2266                 fRun = atoi(gSystem->Getenv("DC_RUN"));
2267         }
2268     } else {
2269         if (gSystem->Getenv("DC_RUN")) {
2270                 AliInfo(Form("Run number already set (%d): DC_RUN variable ignored!", fRun));
2271         }
2272     }
2273     
2274     AliInfo(Form("Run number = %d", fRun)); 
2275 }
2276
2277 //---------------------------------------------------------------------
2278 void AliSimulation::WriteGRPEntry()
2279 {
2280   // Get the necessary information from galice (generator, trigger etc) and
2281   // write a GRP entry corresponding to the settings in the Config.C used
2282   // note that Hall probes and Cavern and Surface Atmos pressures are not simulated.
2283
2284
2285   AliInfo("Writing global run parameters entry into the OCDB");
2286
2287   AliGRPObject* grpObj = new AliGRPObject();
2288
2289   grpObj->SetRunType("PHYSICS");
2290   grpObj->SetTimeStart(fTimeStart);
2291   grpObj->SetTimeEnd(fTimeEnd); 
2292   grpObj->SetBeamEnergyIsSqrtSHalfGeV(); // new format of GRP: store sqrt(s)/2 in GeV
2293
2294   const AliGenerator *gen = gAlice->GetMCApp()->Generator();
2295   Int_t a = 0;
2296   Int_t z = 0;
2297
2298   if (gen) {
2299     TString projectile;
2300     gen->GetProjectile(projectile,a,z);
2301     TString target;
2302     gen->GetTarget(target,a,z);
2303     TString beamType = projectile + "-" + target;
2304     beamType.ReplaceAll(" ","");
2305     if (!beamType.CompareTo("-")) {
2306       grpObj->SetBeamType("UNKNOWN");
2307       grpObj->SetBeamEnergy(gen->GetEnergyCMS()/2);
2308     }
2309     else {
2310       grpObj->SetBeamType(beamType);
2311       if (z != 0) {
2312           grpObj->SetBeamEnergy(gen->GetEnergyCMS()/2 * a / z);
2313       } else {
2314           grpObj->SetBeamEnergy(gen->GetEnergyCMS()/2 );
2315       }
2316       // Heavy ion run, the event specie is set to kHighMult
2317       fEventSpecie = AliRecoParam::kHighMult;
2318       if ((strcmp(beamType,"p-p") == 0) ||
2319           (strcmp(beamType,"p-")  == 0) ||
2320           (strcmp(beamType,"-p")  == 0) ||
2321           (strcmp(beamType,"P-P") == 0) ||
2322           (strcmp(beamType,"P-")  == 0) ||
2323           (strcmp(beamType,"-P")  == 0)) {
2324         // Proton run, the event specie is set to kLowMult
2325         fEventSpecie = AliRecoParam::kLowMult;
2326       } 
2327     }
2328   } else {
2329     AliWarning("Unknown beam type and energy! Setting energy to 0");
2330     grpObj->SetBeamEnergy(0);
2331     grpObj->SetBeamType("UNKNOWN");
2332   }
2333
2334   UInt_t detectorPattern  = 0;
2335   Int_t nDets = 0;
2336   TObjArray *detArray = gAlice->Detectors();
2337   for (Int_t iDet = 0; iDet < AliDAQ::kNDetectors-1; iDet++) {
2338     if (detArray->FindObject(AliDAQ::OfflineModuleName(iDet))) {
2339       detectorPattern |= (1 << iDet);
2340       nDets++;
2341     }
2342   }
2343   // CTP
2344   if (!fTriggerConfig.IsNull())
2345     detectorPattern |= (1 << AliDAQ::DetectorID("TRG"));
2346
2347   // HLT
2348   if (!fRunHLT.IsNull())
2349     detectorPattern |= (1 << AliDAQ::kHLTId);
2350
2351   grpObj->SetNumberOfDetectors((Char_t)nDets);
2352   grpObj->SetDetectorMask((Int_t)detectorPattern);
2353   grpObj->SetLHCPeriod("LHC08c");
2354   grpObj->SetLHCState("STABLE_BEAMS");
2355   //
2356   AliMagF *field = (AliMagF*)TGeoGlobalMagField::Instance()->GetField();
2357   Float_t solenoidField = field ? TMath::Abs(field->SolenoidField()) : 0;
2358
2359   Float_t factorSol     = field ? field->GetFactorSol() : 0;
2360   Float_t currentSol    = TMath::Abs(factorSol)>1E-6 ? 
2361     TMath::Nint(TMath::Abs(solenoidField/factorSol))/5.*30000.*TMath::Abs(factorSol) : 0;
2362   //
2363   Float_t factorDip     = field ? field->GetFactorDip() : 0;
2364   Float_t currentDip    = 6000.*TMath::Abs(factorDip);
2365   //
2366   grpObj->SetL3Current(currentSol,(AliGRPObject::Stats)0);
2367   grpObj->SetDipoleCurrent(currentDip,(AliGRPObject::Stats)0);  
2368   grpObj->SetL3Polarity(factorSol>0 ? 0:1);  
2369   grpObj->SetDipolePolarity(factorDip>0 ? 0:1);
2370   if (field) grpObj->SetUniformBMap(field->IsUniform()); // for special MC with k5kGUniform map
2371   grpObj->SetPolarityConventionLHC();                    // LHC convention +/+ current -> -/- field main components
2372   //
2373   grpObj->SetCavernTemperature(0,(AliGRPObject::Stats)0);
2374   
2375   //grpMap->Add(new TObjString("fCavernPressure"),new TObjString("0")); ---> not inserted in simulation with the new object, since it is now an AliDCSSensor
2376
2377   // Now store the entry in OCDB
2378   AliCDBManager* man = AliCDBManager::Instance();
2379   
2380   man->SetLock(0, fKey);
2381   
2382   AliCDBStorage* sto = man->GetStorage(fGRPWriteLocation.Data());
2383   
2384
2385   AliCDBId id("GRP/GRP/Data", man->GetRun(), man->GetRun(), 1, 1);
2386   AliCDBMetaData *metadata= new AliCDBMetaData();
2387
2388   metadata->SetResponsible("alice-off@cern.ch");
2389   metadata->SetComment("Automatically produced GRP entry for Monte Carlo");
2390  
2391   sto->Put(grpObj,id,metadata);
2392   man->SetLock(1, fKey);
2393 }
2394
2395 //_____________________________________________________________________________
2396 time_t AliSimulation::GenerateTimeStamp() const
2397 {
2398   // Generate event time-stamp according to
2399   // SOR/EOR time from GRP
2400   if (fUseTimeStampFromCDB)
2401     return fTimeStart + gRandom->Integer(fTimeEnd-fTimeStart);
2402   else
2403     return 0;
2404 }