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