]> git.uio.no Git - u/mrichter/AliRoot.git/blob - STEER/AliSimulation.cxx
GetNumberOfVerices()
[u/mrichter/AliRoot.git] / STEER / AliSimulation.cxx
1 /**************************************************************************
2  * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
3  *                                                                        *
4  * Author: The ALICE Off-line Project.                                    *
5  * Contributors are mentioned in the code where appropriate.              *
6  *                                                                        *
7  * Permission to use, copy, modify and distribute this software and its   *
8  * documentation strictly for non-commercial purposes is hereby granted   *
9  * without fee, provided that the above copyright notice appears in all   *
10  * copies and that both the copyright notice and this permission notice   *
11  * appear in the supporting documentation. The authors make no claims     *
12  * about the suitability of this software for any purpose. It is          *
13  * provided "as is" without express or implied warranty.                  *
14  **************************************************************************/
15
16 /* $Id$ */
17
18 ///////////////////////////////////////////////////////////////////////////////
19 //                                                                           //
20 // class for running generation, simulation and digitization                 //
21 //                                                                           //
22 // Hits, sdigits and digits are created for all detectors by typing:         //
23 //                                                                           //
24 //   AliSimulation sim;                                                      //
25 //   sim.Run();                                                              //
26 //                                                                           //
27 // The Run method returns kTRUE in case of successful execution.             //
28 // The number of events can be given as argument to the Run method or it     //
29 // can be set by                                                             //
30 //                                                                           //
31 //   sim.SetNumberOfEvents(n);                                               //
32 //                                                                           //
33 // The name of the configuration file can be passed as argument to the       //
34 // AliSimulation constructor or can be specified by                          //
35 //                                                                           //
36 //   sim.SetConfigFile("...");                                               //
37 //                                                                           //
38 // The generation of particles and the simulation of detector hits can be    //
39 // switched on or off by                                                     //
40 //                                                                           //
41 //   sim.SetRunGeneration(kTRUE);   // generation of primary particles       //
42 //   sim.SetRunSimulation(kFALSE);  // but no tracking                       //
43 //                                                                           //
44 // For which detectors sdigits and digits will be created, can be steered    //
45 // by                                                                        //
46 //                                                                           //
47 //   sim.SetMakeSDigits("ALL");     // make sdigits for all detectors        //
48 //   sim.SetMakeDigits("ITS TPC");  // make digits only for ITS and TPC      //
49 //                                                                           //
50 // The argument is a (case sensitive) string with the names of the           //
51 // detectors separated by a space. An empty string ("") can be used to       //
52 // disable the creation of sdigits or digits. The special string "ALL"       //
53 // selects all available detectors. This is the default.                     //
54 //                                                                           //
55 // The creation of digits from hits instead of from sdigits can be selected  //
56 // by                                                                        //
57 //                                                                           //
58 //   sim.SetMakeDigitsFromHits("TRD");                                       //
59 //                                                                           //
60 // The argument is again a string with the selected detectors. Be aware that //
61 // this feature is not available for all detectors and that merging is not   //
62 // possible, when digits are created directly from hits.                     //
63 //                                                                           //
64 // Background events can be merged by calling                                //
65 //                                                                           //
66 //   sim.MergeWith("background/galice.root", 2);                             //
67 //                                                                           //
68 // The first argument is the file name of the background galice file. The    //
69 // second argument is the number of signal events per background event.      //
70 // By default this number is calculated from the number of available         //
71 // background events. MergeWith can be called several times to merge more    //
72 // than two event streams. It is assumed that the sdigits were already       //
73 // produced for the background events.                                       //
74 //                                                                           //
75 // The output of raw data can be switched on by calling                      //
76 //                                                                           //
77 //   sim.SetWriteRawData("MUON");   // write raw data for MUON               //
78 //                                                                           //
79 // The default output format of the raw data are DDL files. They are         //
80 // converted to a DATE file, if a file name is given as second argument.     //
81 // For this conversion the program "dateStream" is required. If the file     //
82 // name has the extension ".root", the DATE file is converted to a root      //
83 // file. The program "alimdc" is used for this purpose. For the conversion   //
84 // to DATE and root format the two conversion programs have to be installed. //
85 // Only the raw data in the final format is kept if the third argument is    //
86 // kTRUE.                                                                    //
87 //                                                                           //
88 // The methods RunSimulation, RunSDigitization, RunDigitization,             //
89 // RunHitsDigitization and WriteRawData can be used to run only parts of     //
90 // the full simulation chain. The creation of raw data DDL files and their   //
91 // conversion to the DATE or root format can be run directly by calling      //
92 // the methods WriteRawFiles, ConvertRawFilesToDate and ConvertDateToRoot.   //
93 //                                                                           //
94 // The default number of events per file, which is usually set in the        //
95 // config file, can be changed for individual detectors and data types       //
96 // by calling                                                                //
97 //                                                                           //
98 //   sim.SetEventsPerFile("PHOS", "Reconstructed Points", 3);                //
99 //                                                                           //
100 // The first argument is the detector, the second one the data type and the  //
101 // last one the number of events per file. Valid data types are "Hits",      //
102 // "Summable Digits", "Digits", "Reconstructed Points" and "Tracks".         //
103 // The number of events per file has to be set before the simulation of      //
104 // hits. Otherwise it has no effect.                                         //
105 //                                                                           //
106 ///////////////////////////////////////////////////////////////////////////////
107
108 #include <TVirtualMCApplication.h>
109 #include <TGeoManager.h>
110 #include <TObjString.h>
111 #include <TSystem.h>
112 #include <TFile.h>
113
114 #include "AliCodeTimer.h"
115 #include "AliCDBStorage.h"
116 #include "AliCDBEntry.h"
117 #include "AliCDBManager.h"
118 #include "AliGeomManager.h"
119 #include "AliAlignObj.h"
120 #include "AliCentralTrigger.h"
121 #include "AliDAQ.h"
122 #include "AliDigitizer.h"
123 #include "AliGenerator.h"
124 #include "AliLog.h"
125 #include "AliModule.h"
126 #include "AliRun.h"
127 #include "AliRunDigitizer.h"
128 #include "AliRunLoader.h"
129 #include "AliSimulation.h"
130 #include "AliVertexGenFile.h"
131 #include "AliCentralTrigger.h"
132 #include "AliCTPRawData.h"
133 #include "AliRawReaderFile.h"
134 #include "AliRawReaderRoot.h"
135 #include "AliRawReaderDate.h"
136 #include "AliESD.h"
137 #include "AliHeader.h"
138 #include "AliGenEventHeader.h"
139 #include "AliMC.h"
140 #include "AliHLTSimulation.h"
141 #include "AliQADataMakerSteer.h"
142 #include "AliSysInfo.h"
143
144 ClassImp(AliSimulation)
145
146 AliSimulation *AliSimulation::fgInstance = 0;
147 const char* AliSimulation::fgkDetectorName[AliSimulation::fgkNDetectors] = {"ITS", "TPC", "TRD", "TOF", "PHOS", "HMPID", "EMCAL", "MUON", "FMD", "ZDC", "PMD", "T0", "VZERO", "ACORDE", "HLT"};
148
149 //_____________________________________________________________________________
150 AliSimulation::AliSimulation(const char* configFileName,
151                              const char* name, const char* title) :
152   TNamed(name, title),
153
154   fRunGeneration(kTRUE),
155   fRunSimulation(kTRUE),
156   fLoadAlignFromCDB(kTRUE),
157   fLoadAlObjsListOfDets("ALL"),
158   fMakeSDigits("ALL"),
159   fMakeDigits("ALL"),
160   fMakeTrigger(""),
161   fMakeDigitsFromHits(""),
162   fWriteRawData(""),
163   fRawDataFileName(""),
164   fDeleteIntermediateFiles(kFALSE),
165   fWriteSelRawData(kFALSE),
166   fStopOnError(kFALSE),
167
168   fNEvents(1),
169   fConfigFileName(configFileName),
170   fGAliceFileName("galice.root"),
171   fEventsPerFile(),
172   fBkgrdFileNames(NULL),
173   fAlignObjArray(NULL),
174   fUseBkgrdVertex(kTRUE),
175   fRegionOfInterest(kFALSE),
176   fCDBUri(""),
177   fSpecCDBUri(),
178   fRun(-1),
179   fSeed(0),
180   fInitCDBCalled(kFALSE),
181   fInitRunNumberCalled(kFALSE),
182   fSetRunNumberFromDataCalled(kFALSE),
183   fEmbeddingFlag(kFALSE),
184   fRunQA(kTRUE), 
185   fRunHLT("default")
186 {
187 // create simulation object with default parameters
188   fgInstance = this;
189   SetGAliceFile("galice.root");
190   
191 // for QA
192    for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) 
193         fQACycles[iDet] = 999999;
194 }
195
196 //_____________________________________________________________________________
197 AliSimulation::AliSimulation(const AliSimulation& sim) :
198   TNamed(sim),
199
200   fRunGeneration(sim.fRunGeneration),
201   fRunSimulation(sim.fRunSimulation),
202   fLoadAlignFromCDB(sim.fLoadAlignFromCDB),
203   fLoadAlObjsListOfDets(sim.fLoadAlObjsListOfDets),
204   fMakeSDigits(sim.fMakeSDigits),
205   fMakeDigits(sim.fMakeDigits),
206   fMakeTrigger(sim.fMakeTrigger),
207   fMakeDigitsFromHits(sim.fMakeDigitsFromHits),
208   fWriteRawData(sim.fWriteRawData),
209   fRawDataFileName(""),
210   fDeleteIntermediateFiles(kFALSE),
211   fWriteSelRawData(kFALSE),
212   fStopOnError(sim.fStopOnError),
213
214   fNEvents(sim.fNEvents),
215   fConfigFileName(sim.fConfigFileName),
216   fGAliceFileName(sim.fGAliceFileName),
217   fEventsPerFile(),
218   fBkgrdFileNames(NULL),
219   fAlignObjArray(NULL),
220   fUseBkgrdVertex(sim.fUseBkgrdVertex),
221   fRegionOfInterest(sim.fRegionOfInterest),
222   fCDBUri(sim.fCDBUri),
223   fSpecCDBUri(),
224   fRun(-1),
225   fSeed(0),
226   fInitCDBCalled(sim.fInitCDBCalled),
227   fInitRunNumberCalled(sim.fInitRunNumberCalled),
228   fSetRunNumberFromDataCalled(sim.fSetRunNumberFromDataCalled),
229   fEmbeddingFlag(sim.fEmbeddingFlag),
230   fRunQA(kTRUE), 
231   fRunHLT(sim.fRunHLT)
232 {
233 // copy constructor
234
235   for (Int_t i = 0; i < sim.fEventsPerFile.GetEntriesFast(); i++) {
236     if (!sim.fEventsPerFile[i]) continue;
237     fEventsPerFile.Add(sim.fEventsPerFile[i]->Clone());
238   }
239
240   fBkgrdFileNames = new TObjArray;
241   for (Int_t i = 0; i < sim.fBkgrdFileNames->GetEntriesFast(); i++) {
242     if (!sim.fBkgrdFileNames->At(i)) continue;
243     fBkgrdFileNames->Add(sim.fBkgrdFileNames->At(i)->Clone());
244   }
245
246   for (Int_t i = 0; i < sim.fSpecCDBUri.GetEntriesFast(); i++) {
247     if (sim.fSpecCDBUri[i]) fSpecCDBUri.Add(sim.fSpecCDBUri[i]->Clone());
248   }
249   fgInstance = this;
250
251 // for QA
252    for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) 
253         fQACycles[iDet] = sim.fQACycles[iDet];
254 }
255
256 //_____________________________________________________________________________
257 AliSimulation& AliSimulation::operator = (const AliSimulation& sim)
258 {
259 // assignment operator
260
261   this->~AliSimulation();
262   new(this) AliSimulation(sim);
263   return *this;
264 }
265
266 //_____________________________________________________________________________
267 AliSimulation::~AliSimulation()
268 {
269 // clean up
270
271   fEventsPerFile.Delete();
272 //  if(fAlignObjArray) fAlignObjArray->Delete(); // fAlignObjArray->RemoveAll() ???
273 //  delete fAlignObjArray; fAlignObjArray=0;
274
275   if (fBkgrdFileNames) {
276     fBkgrdFileNames->Delete();
277     delete fBkgrdFileNames;
278   }
279
280   fSpecCDBUri.Delete();
281   if (fgInstance==this) fgInstance = 0;
282
283   AliCodeTimer::Instance()->Print();
284 }
285
286
287 //_____________________________________________________________________________
288 void AliSimulation::SetNumberOfEvents(Int_t nEvents)
289 {
290 // set the number of events for one run
291
292   fNEvents = nEvents;
293 }
294
295 //_____________________________________________________________________________
296 void AliSimulation::InitCDB()
297 {
298 // activate a default CDB storage
299 // First check if we have any CDB storage set, because it is used 
300 // to retrieve the calibration and alignment constants
301
302   if (fInitCDBCalled) return;
303   fInitCDBCalled = kTRUE;
304
305   AliCDBManager* man = AliCDBManager::Instance();
306   if (man->IsDefaultStorageSet())
307   {
308     AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
309     AliWarning("Default CDB storage has been already set !");
310     AliWarning(Form("Ignoring the default storage declared in AliSimulation: %s",fCDBUri.Data()));
311     AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
312     fCDBUri = man->GetDefaultStorage()->GetURI();
313   }
314   else {
315     if (fCDBUri.Length() > 0) 
316     {
317         AliDebug(2,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
318         AliDebug(2, Form("Default CDB storage is set to: %s", fCDBUri.Data()));
319         AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
320     } else {
321         fCDBUri="local://$ALICE_ROOT";
322         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
323         AliWarning("Default CDB storage not yet set !!!!");
324         AliWarning(Form("Setting it now to: %s", fCDBUri.Data()));
325         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
326                 
327     }
328     man->SetDefaultStorage(fCDBUri);
329   }
330
331   // Now activate the detector specific CDB storage locations
332   for (Int_t i = 0; i < fSpecCDBUri.GetEntriesFast(); i++) {
333     TObject* obj = fSpecCDBUri[i];
334     if (!obj) continue;
335     AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
336     AliDebug(2, Form("Specific CDB storage for %s is set to: %s",obj->GetName(),obj->GetTitle()));
337     AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
338     man->SetSpecificStorage(obj->GetName(), obj->GetTitle());
339   }
340       
341 }
342
343 //_____________________________________________________________________________
344 void AliSimulation::InitRunNumber(){
345 // check run number. If not set, set it to 0 !!!!
346   
347   if (fInitRunNumberCalled) return;
348   fInitRunNumberCalled = kTRUE;
349   
350   AliCDBManager* man = AliCDBManager::Instance();
351   if (man->GetRun() >= 0)
352   {
353         AliFatal(Form("Run number cannot be set in AliCDBManager before start of simulation: "
354                         "Use external variable DC_RUN or AliSimulation::SetRun()!"));
355   }
356     
357   if(fRun >= 0) {
358         AliDebug(2,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
359         AliDebug(2, Form("Setting CDB run number to: %d",fRun));
360         AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
361   } else {
362         fRun=0;
363         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
364         AliWarning("Run number not yet set !!!!");
365         AliWarning(Form("Setting it now to: %d", fRun));
366         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
367         
368   }
369   man->SetRun(fRun);
370
371   man->Print();
372
373 }
374
375 //_____________________________________________________________________________
376 void AliSimulation::SetCDBLock() {
377   // Set CDB lock: from now on it is forbidden to reset the run number
378   // or the default storage or to activate any further storage!
379   
380   AliCDBManager::Instance()->SetLock(1);
381 }
382
383 //_____________________________________________________________________________
384 void AliSimulation::SetDefaultStorage(const char* uri) {
385 // Store the desired default CDB storage location
386 // Activate it later within the Run() method
387
388   fCDBUri = uri;
389
390 }
391
392 //_____________________________________________________________________________
393 void AliSimulation::SetSpecificStorage(const char* calibType, const char* uri) {
394 // Store a detector-specific CDB storage location
395 // Activate it later within the Run() method
396
397   AliCDBPath aPath(calibType);
398   if(!aPath.IsValid()){
399         AliError(Form("Not a valid path: %s", calibType));
400         return;
401   }
402
403   TObject* obj = fSpecCDBUri.FindObject(calibType);
404   if (obj) fSpecCDBUri.Remove(obj);
405   fSpecCDBUri.Add(new TNamed(calibType, uri));
406
407 }
408
409 //_____________________________________________________________________________
410 void AliSimulation::SetRunNumber(Int_t run)
411 {
412 // sets run number
413 // Activate it later within the Run() method
414
415         fRun = run;
416 }
417
418 //_____________________________________________________________________________
419 void AliSimulation::SetSeed(Int_t seed)
420 {
421 // sets seed number
422 // Activate it later within the Run() method
423
424         fSeed = seed;
425 }
426
427 //_____________________________________________________________________________
428 Bool_t AliSimulation::SetRunNumberFromData()
429 {
430   // Set the CDB manager run number
431   // The run number is retrieved from gAlice
432
433     if (fSetRunNumberFromDataCalled) return kTRUE;
434     fSetRunNumberFromDataCalled = kTRUE;    
435   
436     AliCDBManager* man = AliCDBManager::Instance();
437     Int_t runData = -1, runCDB = -1;
438   
439     AliRunLoader* runLoader = LoadRun("READ");
440     if (!runLoader) return kFALSE;
441     else {
442         runData = runLoader->GetAliRun()->GetHeader()->GetRun();
443         delete runLoader;
444     }
445   
446     runCDB = man->GetRun();
447     if(runCDB >= 0) {
448         if (runCDB != runData) {
449                 AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
450                 AliWarning(Form("A run number was previously set in AliCDBManager: %d !", runCDB));
451                 AliWarning(Form("It will be replaced with the run number got from run header: %d !", runData));
452                 AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");    
453         }
454         
455     }
456       
457     man->SetRun(runData);
458     fRun = runData;
459     
460     if(man->GetRun() < 0) {
461         AliError("Run number not properly initalized!");
462         return kFALSE;
463     }
464   
465     man->Print();
466     
467     return kTRUE;
468 }
469
470 //_____________________________________________________________________________
471 void AliSimulation::SetConfigFile(const char* fileName)
472 {
473 // set the name of the config file
474
475   fConfigFileName = fileName;
476 }
477
478 //_____________________________________________________________________________
479 void AliSimulation::SetGAliceFile(const char* fileName)
480 {
481 // set the name of the galice file
482 // the path is converted to an absolute one if it is relative
483
484   fGAliceFileName = fileName;
485   if (!gSystem->IsAbsoluteFileName(fGAliceFileName)) {
486     char* absFileName = gSystem->ConcatFileName(gSystem->WorkingDirectory(),
487                                                 fGAliceFileName);
488     fGAliceFileName = absFileName;
489     delete[] absFileName;
490   }
491
492   AliDebug(2, Form("galice file name set to %s", fileName));
493 }
494
495 //_____________________________________________________________________________
496 void AliSimulation::SetEventsPerFile(const char* detector, const char* type, 
497                                      Int_t nEvents)
498 {
499 // set the number of events per file for the given detector and data type
500 // ("Hits", "Summable Digits", "Digits", "Reconstructed Points" or "Tracks")
501
502   TNamed* obj = new TNamed(detector, type);
503   obj->SetUniqueID(nEvents);
504   fEventsPerFile.Add(obj);
505 }
506
507 //_____________________________________________________________________________
508 Bool_t AliSimulation::MisalignGeometry(AliRunLoader *runLoader)
509 {
510   // Read the alignment objects from CDB.
511   // Each detector is supposed to have the
512   // alignment objects in DET/Align/Data CDB path.
513   // All the detector objects are then collected,
514   // sorted by geometry level (starting from ALIC) and
515   // then applied to the TGeo geometry.
516   // Finally an overlaps check is performed.
517
518   if (!AliGeomManager::GetGeometry() || !AliGeomManager::GetGeometry()->IsClosed()) {
519     AliError("Can't apply the misalignment! Geometry is not loaded or it is still opened!");
520     return kFALSE;
521   }  
522   
523   // initialize CDB storage, run number, set CDB lock
524   InitCDB();
525 //  if (!SetRunNumberFromData()) if (fStopOnError) return kFALSE;
526   SetCDBLock();
527     
528   Bool_t delRunLoader = kFALSE;
529   if (!runLoader) {
530     runLoader = LoadRun("READ");
531     if (!runLoader) return kFALSE;
532     delRunLoader = kTRUE;
533   }
534   
535   // Export ideal geometry 
536   if(!gAlice->IsRootGeometry()) AliGeomManager::GetGeometry()->Export("geometry.root");
537
538   // Load alignment data from CDB and apply to geometry through AliGeomManager
539   if(fLoadAlignFromCDB){
540     
541     TString detStr = fLoadAlObjsListOfDets;
542     TString loadAlObjsListOfDets = "";
543     
544     TObjArray* detArray = runLoader->GetAliRun()->Detectors();
545     for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
546       AliModule* det = (AliModule*) detArray->At(iDet);
547       if (!det || !det->IsActive()) continue;
548       if (IsSelected(det->GetName(), detStr)) {
549         //add det to list of dets to be aligned from CDB
550         loadAlObjsListOfDets += det->GetName();
551         loadAlObjsListOfDets += " ";
552       }
553     } // end loop over detectors
554     loadAlObjsListOfDets.Prepend("GRP "); //add alignment objects for non-sensitive modules
555     AliGeomManager::ApplyAlignObjsFromCDB(loadAlObjsListOfDets.Data());
556   }else{
557     // Check if the array with alignment objects was
558     // provided by the user. If yes, apply the objects
559     // to the present TGeo geometry
560     if (fAlignObjArray) {
561       if (AliGeomManager::ApplyAlignObjsToGeom(*fAlignObjArray) == kFALSE) {
562         AliError("The misalignment of one or more volumes failed!"
563                  "Compare the list of simulated detectors and the list of detector alignment data!");
564         if (delRunLoader) delete runLoader;
565         return kFALSE;
566       }
567     }
568   }
569
570   // Update the internal geometry of modules (ITS needs it)
571   TString detStr = fLoadAlObjsListOfDets;
572   TObjArray* detArray = runLoader->GetAliRun()->Detectors();
573   for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
574
575     AliModule* det = (AliModule*) detArray->At(iDet);
576     if (!det || !det->IsActive()) continue;
577     if (IsSelected(det->GetName(), detStr)) {
578       det->UpdateInternalGeometry();
579     }
580   } // end loop over detectors
581
582
583   if (delRunLoader) delete runLoader;
584
585   return kTRUE;
586 }
587
588 //_____________________________________________________________________________
589 void AliSimulation::MergeWith(const char* fileName, Int_t nSignalPerBkgrd)
590 {
591 // add a file with background events for merging
592
593   TObjString* fileNameStr = new TObjString(fileName);
594   fileNameStr->SetUniqueID(nSignalPerBkgrd);
595   if (!fBkgrdFileNames) fBkgrdFileNames = new TObjArray;
596   fBkgrdFileNames->Add(fileNameStr);
597 }
598
599 void AliSimulation::EmbedInto(const char* fileName, Int_t nSignalPerBkgrd)
600 {
601 // add a file with background events for embeddin
602   MergeWith(fileName, nSignalPerBkgrd);
603   fEmbeddingFlag = kTRUE;
604 }
605
606 //_____________________________________________________________________________
607 Bool_t AliSimulation::Run(Int_t nEvents)
608 {
609 // run the generation, simulation and digitization
610
611  
612   AliCodeTimerAuto("")
613   
614   // Load run number and seed from environmental vars
615   ProcessEnvironmentVars();
616
617   gRandom->SetSeed(fSeed);
618    
619   if (nEvents > 0) fNEvents = nEvents;
620
621   // generation and simulation -> hits
622   if (fRunGeneration) {
623     if (!RunSimulation()) if (fStopOnError) return kFALSE;
624   }
625            
626   // initialize CDB storage from external environment
627   // (either CDB manager or AliSimulation setters),
628   // if not already done in RunSimulation()
629   InitCDB();
630   
631   // Set run number in CDBManager from data 
632   // From this point on the run number must be always loaded from data!
633   if (!SetRunNumberFromData()) if (fStopOnError) return kFALSE;
634   
635   // Set CDB lock: from now on it is forbidden to reset the run number
636   // or the default storage or to activate any further storage!
637   SetCDBLock();
638
639   // If RunSimulation was not called, load the geometry and misalign it
640   if (!AliGeomManager::GetGeometry()) {
641     // Initialize the geometry manager
642     AliGeomManager::LoadGeometry("geometry.root");
643     
644 //    // Check that the consistency of symbolic names for the activated subdetectors
645 //    // in the geometry loaded by AliGeomManager
646 //    AliRunLoader* runLoader = LoadRun("READ");
647 //    if (!runLoader) return kFALSE;
648 //
649 //    TString detsToBeChecked = "";
650 //    TObjArray* detArray = runLoader->GetAliRun()->Detectors();
651 //    for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
652 //      AliModule* det = (AliModule*) detArray->At(iDet);
653 //      if (!det || !det->IsActive()) continue;
654 //      detsToBeChecked += det->GetName();
655 //      detsToBeChecked += " ";
656 //    } // end loop over detectors
657 //    if(!AliGeomManager::CheckSymNamesLUT(detsToBeChecked.Data()))
658     if(!AliGeomManager::CheckSymNamesLUT("ALL"))
659         AliFatalClass("Current loaded geometry differs in the definition of symbolic names!");
660         
661     if (!AliGeomManager::GetGeometry()) if (fStopOnError) return kFALSE;
662     // Misalign geometry
663     if(!MisalignGeometry()) if (fStopOnError) return kFALSE;
664   }
665
666
667   // hits -> summable digits
668   AliSysInfo::AddStamp("Start_sdigitization");
669   if (!fMakeSDigits.IsNull()) {
670     if (!RunSDigitization(fMakeSDigits)) if (fStopOnError) return kFALSE;
671  
672   }
673   AliSysInfo::AddStamp("Stop_sdigitization");
674   
675   AliSysInfo::AddStamp("Start_digitization");  
676   // summable digits -> digits  
677   if (!fMakeDigits.IsNull()) {
678     if (!RunDigitization(fMakeDigits, fMakeDigitsFromHits)) {
679       if (fStopOnError) return kFALSE;
680     }
681    }
682   AliSysInfo::AddStamp("Stop_digitization");
683
684   
685   
686   // hits -> digits
687   if (!fMakeDigitsFromHits.IsNull()) {
688     if (fBkgrdFileNames && (fBkgrdFileNames->GetEntriesFast() > 0)) {
689       AliWarning(Form("Merging and direct creation of digits from hits " 
690                  "was selected for some detectors. "
691                  "No merging will be done for the following detectors: %s",
692                  fMakeDigitsFromHits.Data()));
693     }
694     if (!RunHitsDigitization(fMakeDigitsFromHits)) {
695       if (fStopOnError) return kFALSE;
696     }
697   }
698
699   
700   
701   // digits -> trigger
702   if (!RunTrigger(fMakeTrigger,fMakeDigits)) {
703     if (fStopOnError) return kFALSE;
704   }
705
706   
707   
708   // digits -> raw data
709   if (!fWriteRawData.IsNull()) {
710     if (!WriteRawData(fWriteRawData, fRawDataFileName, 
711                       fDeleteIntermediateFiles,fWriteSelRawData)) {
712       if (fStopOnError) return kFALSE;
713     }
714   }
715
716   
717   
718   // run HLT simulation
719   if (!fRunHLT.IsNull()) {
720     if (!RunHLT()) {
721       if (fStopOnError) return kFALSE;
722     }
723   }
724   
725   //QA
726         if (fRunQA) {
727                 Bool_t rv = RunQA() ; 
728                 if (!rv)
729                         if (fStopOnError) 
730                                 return kFALSE ;         
731         }
732
733   // Cleanup of CDB manager: cache and active storages!
734   AliCDBManager::Instance()->ClearCache();
735
736   return kTRUE;
737 }
738
739 //_____________________________________________________________________________
740 Bool_t AliSimulation::RunTrigger(const char* config, const char* detectors)
741 {
742   // run the trigger
743
744   AliCodeTimerAuto("")
745
746   // initialize CDB storage from external environment
747   // (either CDB manager or AliSimulation setters),
748   // if not already done in RunSimulation()
749   InitCDB();
750   
751   // Set run number in CDBManager from data 
752   // From this point on the run number must be always loaded from data!
753   if (!SetRunNumberFromData()) if (fStopOnError) return kFALSE;
754   
755   // Set CDB lock: from now on it is forbidden to reset the run number
756   // or the default storage or to activate any further storage!
757   SetCDBLock();
758    
759    AliRunLoader* runLoader = LoadRun("READ");
760    if (!runLoader) return kFALSE;
761    TString trconfiguration = config;
762
763    if (trconfiguration.IsNull()) {
764      if (gAlice->GetTriggerDescriptor() != "") {
765        trconfiguration = gAlice->GetTriggerDescriptor();
766      }
767      else
768        AliWarning("No trigger descriptor is specified. Loading the one that is in the CDB.");
769    }
770
771    runLoader->MakeTree( "GG" );
772    AliCentralTrigger* aCTP = runLoader->GetTrigger();
773    // Load Configuration
774    if (!aCTP->LoadConfiguration( trconfiguration ))
775      return kFALSE;
776
777    // digits -> trigger
778    if( !aCTP->RunTrigger( runLoader , detectors ) ) {
779       if (fStopOnError) {
780         //  delete aCTP;
781         return kFALSE;
782       }
783    }
784
785    delete runLoader;
786
787    return kTRUE;
788 }
789
790 //_____________________________________________________________________________
791 Bool_t AliSimulation::WriteTriggerRawData()
792 {
793   // Writes the CTP (trigger) DDL raw data
794   // Details of the format are given in the
795   // trigger TDR - pages 134 and 135.
796   AliCTPRawData writer;
797   writer.RawData();
798
799   return kTRUE;
800 }
801
802 //_____________________________________________________________________________
803 Bool_t AliSimulation::RunSimulation(Int_t nEvents)
804 {
805 // run the generation and simulation
806
807   AliCodeTimerAuto("")
808
809   // initialize CDB storage and run number from external environment
810   // (either CDB manager or AliSimulation setters)
811   InitCDB();
812   InitRunNumber();
813   SetCDBLock();
814   
815   if (!gAlice) {
816     AliError("no gAlice object. Restart aliroot and try again.");
817     return kFALSE;
818   }
819   if (gAlice->Modules()->GetEntries() > 0) {
820     AliError("gAlice was already run. Restart aliroot and try again.");
821     return kFALSE;
822   }
823
824   AliInfo(Form("initializing gAlice with config file %s",
825           fConfigFileName.Data()));
826   StdoutToAliInfo(StderrToAliError(
827     gAlice->Init(fConfigFileName.Data());
828   ););
829   
830   // Get the trigger descriptor string
831   // Either from AliSimulation or from
832   // gAlice
833   if (fMakeTrigger.IsNull()) {
834     if (gAlice->GetTriggerDescriptor() != "")
835       fMakeTrigger = gAlice->GetTriggerDescriptor();
836   }
837   else
838     gAlice->SetTriggerDescriptor(fMakeTrigger.Data());
839
840   // Set run number in CDBManager
841   AliInfo(Form("Run number: %d",AliCDBManager::Instance()->GetRun()));
842
843   AliRunLoader* runLoader = gAlice->GetRunLoader();
844   if (!runLoader) {
845              AliError(Form("gAlice has no run loader object. "
846                              "Check your config file: %s", fConfigFileName.Data()));
847              return kFALSE;
848   }
849   SetGAliceFile(runLoader->GetFileName());
850       
851   // Misalign geometry
852 #if ROOT_VERSION_CODE < 331527
853   AliGeomManager::SetGeometry(gGeoManager);
854   
855   // Check that the consistency of symbolic names for the activated subdetectors
856   // in the geometry loaded by AliGeomManager
857   TString detsToBeChecked = "";
858   TObjArray* detArray = runLoader->GetAliRun()->Detectors();
859   for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
860     AliModule* det = (AliModule*) detArray->At(iDet);
861     if (!det || !det->IsActive()) continue;
862     detsToBeChecked += det->GetName();
863     detsToBeChecked += " ";
864   } // end loop over detectors
865   if(!AliGeomManager::CheckSymNamesLUT(detsToBeChecked.Data()))
866     AliFatalClass("Current loaded geometry differs in the definition of symbolic names!");
867   MisalignGeometry(runLoader);
868 #endif
869
870 //   AliRunLoader* runLoader = gAlice->GetRunLoader();
871 //   if (!runLoader) {
872 //     AliError(Form("gAlice has no run loader object. "
873 //                   "Check your config file: %s", fConfigFileName.Data()));
874 //     return kFALSE;
875 //   }
876 //   SetGAliceFile(runLoader->GetFileName());
877
878   if (!gAlice->Generator()) {
879     AliError(Form("gAlice has no generator object. "
880                   "Check your config file: %s", fConfigFileName.Data()));
881     return kFALSE;
882   }
883   if (nEvents <= 0) nEvents = fNEvents;
884
885   // get vertex from background file in case of merging
886   if (fUseBkgrdVertex &&
887       fBkgrdFileNames && (fBkgrdFileNames->GetEntriesFast() > 0)) {
888     Int_t signalPerBkgrd = GetNSignalPerBkgrd(nEvents);
889     const char* fileName = ((TObjString*)
890                             (fBkgrdFileNames->At(0)))->GetName();
891     AliInfo(Form("The vertex will be taken from the background "
892                  "file %s with nSignalPerBackground = %d", 
893                  fileName, signalPerBkgrd));
894     AliVertexGenFile* vtxGen = new AliVertexGenFile(fileName, signalPerBkgrd);
895     gAlice->Generator()->SetVertexGenerator(vtxGen);
896   }
897
898   if (!fRunSimulation) {
899     gAlice->Generator()->SetTrackingFlag(0);
900   }
901
902   // set the number of events per file for given detectors and data types
903   for (Int_t i = 0; i < fEventsPerFile.GetEntriesFast(); i++) {
904     if (!fEventsPerFile[i]) continue;
905     const char* detName = fEventsPerFile[i]->GetName();
906     const char* typeName = fEventsPerFile[i]->GetTitle();
907     TString loaderName(detName);
908     loaderName += "Loader";
909     AliLoader* loader = runLoader->GetLoader(loaderName);
910     if (!loader) {
911       AliError(Form("RunSimulation", "no loader for %s found\n"
912                     "Number of events per file not set for %s %s", 
913                     detName, typeName, detName));
914       continue;
915     }
916     AliDataLoader* dataLoader = 
917       loader->GetDataLoader(typeName);
918     if (!dataLoader) {
919       AliError(Form("no data loader for %s found\n"
920                     "Number of events per file not set for %s %s", 
921                     typeName, detName, typeName));
922       continue;
923     }
924     dataLoader->SetNumberOfEventsPerFile(fEventsPerFile[i]->GetUniqueID());
925     AliDebug(1, Form("number of events per file set to %d for %s %s",
926                      fEventsPerFile[i]->GetUniqueID(), detName, typeName));
927   }
928
929   AliInfo("running gAlice");
930   AliSysInfo::AddStamp("Start_simulation");
931   StdoutToAliInfo(StderrToAliError(
932     gAlice->Run(nEvents);
933   ););
934   AliSysInfo::AddStamp("Stop_simulation");
935   delete runLoader;
936
937   return kTRUE;
938 }
939
940 //_____________________________________________________________________________
941 Bool_t AliSimulation::RunSDigitization(const char* detectors)
942 {
943 // run the digitization and produce summable digits
944   static Int_t eventNr=0;
945   AliCodeTimerAuto("")
946
947   // initialize CDB storage, run number, set CDB lock
948   InitCDB();
949   if (!SetRunNumberFromData()) if (fStopOnError) return kFALSE;
950   SetCDBLock();
951   
952   AliRunLoader* runLoader = LoadRun();
953   if (!runLoader) return kFALSE;
954
955   TString detStr = detectors;
956   TObjArray* detArray = runLoader->GetAliRun()->Detectors();
957   for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
958     AliModule* det = (AliModule*) detArray->At(iDet);
959     if (!det || !det->IsActive()) continue;
960     if (IsSelected(det->GetName(), detStr)) {
961       AliInfo(Form("creating summable digits for %s", det->GetName()));
962       AliCodeTimerAuto(Form("creating summable digits for %s", det->GetName()));
963       det->Hits2SDigits();
964       AliSysInfo::AddStamp(Form("Digit_%s_%d",det->GetName(),eventNr), 0,1, eventNr);
965     }
966   }
967
968   if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
969     AliError(Form("the following detectors were not found: %s",
970                   detStr.Data()));
971     if (fStopOnError) return kFALSE;
972   }
973   eventNr++;
974   delete runLoader;
975
976   return kTRUE;
977 }
978
979
980 //_____________________________________________________________________________
981 Bool_t AliSimulation::RunDigitization(const char* detectors, 
982                                       const char* excludeDetectors)
983 {
984 // run the digitization and produce digits from sdigits
985
986   AliCodeTimerAuto("")
987
988   // initialize CDB storage, run number, set CDB lock
989   InitCDB();
990   if (!SetRunNumberFromData()) if (fStopOnError) return kFALSE;
991   SetCDBLock();
992   
993   while (AliRunLoader::GetRunLoader()) delete AliRunLoader::GetRunLoader();
994   if (gAlice) delete gAlice;
995   gAlice = NULL;
996
997   Int_t nStreams = 1;
998   if (fBkgrdFileNames) nStreams = fBkgrdFileNames->GetEntriesFast() + 1;
999   Int_t signalPerBkgrd = GetNSignalPerBkgrd();
1000   AliRunDigitizer* manager = new AliRunDigitizer(nStreams, signalPerBkgrd);
1001   // manager->SetEmbeddingFlag(fEmbeddingFlag);
1002   manager->SetInputStream(0, fGAliceFileName.Data());
1003   for (Int_t iStream = 1; iStream < nStreams; iStream++) {
1004     const char* fileName = ((TObjString*)
1005                             (fBkgrdFileNames->At(iStream-1)))->GetName();
1006     manager->SetInputStream(iStream, fileName);
1007   }
1008
1009   TString detStr = detectors;
1010   TString detExcl = excludeDetectors;
1011   manager->GetInputStream(0)->ImportgAlice();
1012   AliRunLoader* runLoader = 
1013     AliRunLoader::GetRunLoader(manager->GetInputStream(0)->GetFolderName());
1014   TObjArray* detArray = runLoader->GetAliRun()->Detectors();
1015   for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
1016     AliModule* det = (AliModule*) detArray->At(iDet);
1017     if (!det || !det->IsActive()) continue;
1018     if (IsSelected(det->GetName(), detStr) && 
1019         !IsSelected(det->GetName(), detExcl)) {
1020       AliDigitizer* digitizer = det->CreateDigitizer(manager);
1021       
1022       if (!digitizer) {
1023         AliError(Form("no digitizer for %s", det->GetName()));
1024         if (fStopOnError) return kFALSE;
1025       } else {
1026         digitizer->SetRegionOfInterest(fRegionOfInterest);
1027       }
1028     }
1029   }
1030
1031   if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
1032     AliError(Form("the following detectors were not found: %s", 
1033                   detStr.Data()));
1034     if (fStopOnError) return kFALSE;
1035   }
1036
1037   if (!manager->GetListOfTasks()->IsEmpty()) {
1038     AliInfo("executing digitization");
1039     manager->Exec("");
1040   }
1041
1042   delete manager;
1043
1044   return kTRUE;
1045 }
1046
1047 //_____________________________________________________________________________
1048 Bool_t AliSimulation::RunHitsDigitization(const char* detectors)
1049 {
1050 // run the digitization and produce digits from hits
1051
1052   AliCodeTimerAuto("")
1053
1054   // initialize CDB storage, run number, set CDB lock
1055   InitCDB();
1056   if (!SetRunNumberFromData()) if (fStopOnError) return kFALSE;
1057   SetCDBLock();
1058   
1059   AliRunLoader* runLoader = LoadRun("READ");
1060   if (!runLoader) return kFALSE;
1061
1062   TString detStr = detectors;
1063   TObjArray* detArray = runLoader->GetAliRun()->Detectors();
1064   for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
1065     AliModule* det = (AliModule*) detArray->At(iDet);
1066     if (!det || !det->IsActive()) continue;
1067     if (IsSelected(det->GetName(), detStr)) {
1068       AliInfo(Form("creating digits from hits for %s", det->GetName()));
1069       det->Hits2Digits();
1070     }
1071   }
1072
1073   if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
1074     AliError(Form("the following detectors were not found: %s", 
1075                   detStr.Data()));
1076     if (fStopOnError) return kFALSE;
1077   }
1078
1079   delete runLoader;
1080   //PH Temporary fix to avoid interference with the PHOS loder/getter
1081   //PH The problem has to be solved in more general way 09/06/05
1082
1083   return kTRUE;
1084 }
1085
1086 //_____________________________________________________________________________
1087 Bool_t AliSimulation::WriteRawData(const char* detectors, 
1088                                    const char* fileName,
1089                                    Bool_t deleteIntermediateFiles,
1090                                    Bool_t selrawdata)
1091 {
1092 // convert the digits to raw data
1093 // First DDL raw data files for the given detectors are created.
1094 // If a file name is given, the DDL files are then converted to a DATE file.
1095 // If deleteIntermediateFiles is true, the DDL raw files are deleted 
1096 // afterwards.
1097 // If the file name has the extension ".root", the DATE file is converted
1098 // to a root file.
1099 // If deleteIntermediateFiles is true, the DATE file is deleted afterwards.
1100 // 'selrawdata' flag can be used to enable writing of detectors raw data
1101 // accoring to the trigger cluster.
1102
1103   AliCodeTimerAuto("")
1104
1105   if (!WriteRawFiles(detectors)) {
1106     if (fStopOnError) return kFALSE;
1107   }
1108
1109   TString dateFileName(fileName);
1110   if (!dateFileName.IsNull()) {
1111     Bool_t rootOutput = dateFileName.EndsWith(".root");
1112     if (rootOutput) dateFileName += ".date";
1113     TString selDateFileName;
1114     if (selrawdata) {
1115       selDateFileName = "selected.";
1116       selDateFileName+= dateFileName;
1117     }
1118     if (!ConvertRawFilesToDate(dateFileName,selDateFileName)) {
1119       if (fStopOnError) return kFALSE;
1120     }
1121     if (deleteIntermediateFiles) {
1122       AliRunLoader* runLoader = LoadRun("READ");
1123       if (runLoader) for (Int_t iEvent = 0; 
1124                           iEvent < runLoader->GetNumberOfEvents(); iEvent++) {
1125         char command[256];
1126         sprintf(command, "rm -r raw%d", iEvent);
1127         gSystem->Exec(command);
1128       }
1129     }
1130
1131     if (rootOutput) {
1132       if (!ConvertDateToRoot(dateFileName, fileName)) {
1133         if (fStopOnError) return kFALSE;
1134       }
1135       if (deleteIntermediateFiles) {
1136         gSystem->Unlink(dateFileName);
1137       }
1138       if (selrawdata) {
1139         TString selFileName = "selected.";
1140         selFileName        += fileName;
1141         if (!ConvertDateToRoot(selDateFileName, selFileName)) {
1142           if (fStopOnError) return kFALSE;
1143         }
1144         if (deleteIntermediateFiles) {
1145           gSystem->Unlink(selDateFileName);
1146         }
1147       }
1148     }
1149   }
1150
1151   return kTRUE;
1152 }
1153
1154 //_____________________________________________________________________________
1155 Bool_t AliSimulation::WriteRawFiles(const char* detectors)
1156 {
1157 // convert the digits to raw data DDL files
1158
1159   AliCodeTimerAuto("")
1160   
1161   AliRunLoader* runLoader = LoadRun("READ");
1162   if (!runLoader) return kFALSE;
1163
1164   // write raw data to DDL files
1165   for (Int_t iEvent = 0; iEvent < runLoader->GetNumberOfEvents(); iEvent++) {
1166     AliInfo(Form("processing event %d", iEvent));
1167     runLoader->GetEvent(iEvent);
1168     TString baseDir = gSystem->WorkingDirectory();
1169     char dirName[256];
1170     sprintf(dirName, "raw%d", iEvent);
1171     gSystem->MakeDirectory(dirName);
1172     if (!gSystem->ChangeDirectory(dirName)) {
1173       AliError(Form("couldn't change to directory %s", dirName));
1174       if (fStopOnError) return kFALSE; else continue;
1175     }
1176
1177     TString detStr = detectors;
1178     TObjArray* detArray = runLoader->GetAliRun()->Detectors();
1179     for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
1180       AliModule* det = (AliModule*) detArray->At(iDet);
1181       if (!det || !det->IsActive()) continue;
1182       if (IsSelected(det->GetName(), detStr)) {
1183         AliInfo(Form("creating raw data from digits for %s", det->GetName()));
1184         det->Digits2Raw();
1185       }
1186     }
1187
1188     if (!WriteTriggerRawData())
1189       if (fStopOnError) return kFALSE;
1190
1191     gSystem->ChangeDirectory(baseDir);
1192     if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
1193       AliError(Form("the following detectors were not found: %s", 
1194                     detStr.Data()));
1195       if (fStopOnError) return kFALSE;
1196     }
1197   }
1198
1199   delete runLoader;
1200   
1201   return kTRUE;
1202 }
1203
1204 //_____________________________________________________________________________
1205 Bool_t AliSimulation::ConvertRawFilesToDate(const char* dateFileName,
1206                                             const char* selDateFileName)
1207 {
1208 // convert raw data DDL files to a DATE file with the program "dateStream"
1209 // The second argument is not empty when the user decides to write
1210 // the detectors raw data according to the trigger cluster.
1211
1212   AliCodeTimerAuto("")
1213   
1214   char* path = gSystem->Which(gSystem->Getenv("PATH"), "dateStream");
1215   if (!path) {
1216     AliError("the program dateStream was not found");
1217     if (fStopOnError) return kFALSE;
1218   } else {
1219     delete[] path;
1220   }
1221
1222   AliRunLoader* runLoader = LoadRun("READ");
1223   if (!runLoader) return kFALSE;
1224
1225   AliInfo(Form("converting raw data DDL files to DATE file %s", dateFileName));
1226   Bool_t selrawdata = kFALSE;
1227   if (strcmp(selDateFileName,"") != 0) selrawdata = kTRUE;
1228
1229   char command[256];
1230   // Note the option -s. It is used in order to avoid
1231   // the generation of SOR/EOR events.
1232   sprintf(command, "dateStream -c -s -D -o %s -# %d -C -run %d", 
1233           dateFileName, runLoader->GetNumberOfEvents(),runLoader->GetHeader()->GetRun());
1234   FILE* pipe = gSystem->OpenPipe(command, "w");
1235
1236   Int_t selEvents = 0;
1237   for (Int_t iEvent = 0; iEvent < runLoader->GetNumberOfEvents(); iEvent++) {
1238     fprintf(pipe, "GDC\n");
1239     Float_t ldc = 0;
1240     Int_t prevLDC = -1;
1241
1242     if (selrawdata) {
1243       // Check if the event was triggered by CTP
1244       runLoader->GetEvent(iEvent);
1245       if (!runLoader->LoadTrigger()) {
1246         AliCentralTrigger *aCTP = runLoader->GetTrigger();
1247         if (aCTP->GetClassMask()) selEvents++;
1248       }
1249       else {
1250         AliWarning("No trigger can be loaded! Writing of selected raw data is abandoned !");
1251         selrawdata = kFALSE;
1252       }
1253     }
1254
1255     // loop over detectors and DDLs
1256     for (Int_t iDet = 0; iDet < AliDAQ::kNDetectors; iDet++) {
1257       for (Int_t iDDL = 0; iDDL < AliDAQ::NumberOfDdls(iDet); iDDL++) {
1258
1259         Int_t ddlID = AliDAQ::DdlID(iDet,iDDL);
1260         Int_t ldcID = Int_t(ldc + 0.0001);
1261         ldc += AliDAQ::NumberOfLdcs(iDet) / AliDAQ::NumberOfDdls(iDet);
1262
1263         char rawFileName[256];
1264         sprintf(rawFileName, "raw%d/%s", 
1265                 iEvent, AliDAQ::DdlFileName(iDet,iDDL));
1266
1267         // check existence and size of raw data file
1268         FILE* file = fopen(rawFileName, "rb");
1269         if (!file) continue;
1270         fseek(file, 0, SEEK_END);
1271         unsigned long size = ftell(file);
1272         fclose(file);
1273         if (!size) continue;
1274
1275         if (ldcID != prevLDC) {
1276           fprintf(pipe, " LDC Id %d\n", ldcID);
1277           prevLDC = ldcID;
1278         }
1279         fprintf(pipe, "  Equipment Id %d Payload %s\n", ddlID, rawFileName);
1280       }
1281     }
1282   }
1283
1284   Int_t result = gSystem->ClosePipe(pipe);
1285
1286   if (!(selrawdata && selEvents > 0)) {
1287     delete runLoader;
1288     return (result == 0);
1289   }
1290
1291   AliInfo(Form("converting selected by trigger cluster raw data DDL files to DATE file %s", selDateFileName));
1292   
1293   sprintf(command, "dateStream -c -s -D -o %s -# %d -C -run %d", 
1294           selDateFileName,selEvents,runLoader->GetHeader()->GetRun());
1295   FILE* pipe2 = gSystem->OpenPipe(command, "w");
1296
1297   for (Int_t iEvent = 0; iEvent < runLoader->GetNumberOfEvents(); iEvent++) {
1298
1299     // Get the trigger decision and cluster
1300     TString detClust;
1301     runLoader->GetEvent(iEvent);
1302     if (!runLoader->LoadTrigger()) {
1303       AliCentralTrigger *aCTP = runLoader->GetTrigger();
1304       if (aCTP->GetClassMask() == 0) continue;
1305       detClust = aCTP->GetTriggeredDetectors();
1306       AliInfo(Form("List of detectors to be read out: %s",detClust.Data()));
1307     }
1308
1309     fprintf(pipe2, "GDC\n");
1310     Float_t ldc = 0;
1311     Int_t prevLDC = -1;
1312
1313     // loop over detectors and DDLs
1314     for (Int_t iDet = 0; iDet < AliDAQ::kNDetectors; iDet++) {
1315       // Write only raw data from detectors that
1316       // are contained in the trigger cluster(s)
1317       if (!IsSelected(AliDAQ::DetectorName(iDet),detClust)) continue;
1318
1319       for (Int_t iDDL = 0; iDDL < AliDAQ::NumberOfDdls(iDet); iDDL++) {
1320
1321         Int_t ddlID = AliDAQ::DdlID(iDet,iDDL);
1322         Int_t ldcID = Int_t(ldc + 0.0001);
1323         ldc += AliDAQ::NumberOfLdcs(iDet) / AliDAQ::NumberOfDdls(iDet);
1324
1325         char rawFileName[256];
1326         sprintf(rawFileName, "raw%d/%s", 
1327                 iEvent, AliDAQ::DdlFileName(iDet,iDDL));
1328
1329         // check existence and size of raw data file
1330         FILE* file = fopen(rawFileName, "rb");
1331         if (!file) continue;
1332         fseek(file, 0, SEEK_END);
1333         unsigned long size = ftell(file);
1334         fclose(file);
1335         if (!size) continue;
1336
1337         if (ldcID != prevLDC) {
1338           fprintf(pipe2, " LDC Id %d\n", ldcID);
1339           prevLDC = ldcID;
1340         }
1341         fprintf(pipe2, "  Equipment Id %d Payload %s\n", ddlID, rawFileName);
1342       }
1343     }
1344   }
1345
1346   Int_t result2 = gSystem->ClosePipe(pipe2);
1347
1348   delete runLoader;
1349   return ((result == 0) && (result2 == 0));
1350 }
1351
1352 //_____________________________________________________________________________
1353 Bool_t AliSimulation::ConvertDateToRoot(const char* dateFileName,
1354                                         const char* rootFileName)
1355 {
1356 // convert a DATE file to a root file with the program "alimdc"
1357
1358   // ALIMDC setup
1359   const Int_t kDBSize = 2000000000;
1360   const Int_t kTagDBSize = 1000000000;
1361   const Bool_t kFilter = kFALSE;
1362   const Int_t kCompression = 1;
1363
1364   char* path = gSystem->Which(gSystem->Getenv("PATH"), "alimdc");
1365   if (!path) {
1366     AliError("the program alimdc was not found");
1367     if (fStopOnError) return kFALSE;
1368   } else {
1369     delete[] path;
1370   }
1371
1372   AliInfo(Form("converting DATE file %s to root file %s", 
1373                dateFileName, rootFileName));
1374
1375   const char* rawDBFS[2] = { "/tmp/mdc1", "/tmp/mdc2" };
1376   const char* tagDBFS    = "/tmp/mdc1/tags";
1377
1378   // User defined file system locations
1379   if (gSystem->Getenv("ALIMDC_RAWDB1")) 
1380     rawDBFS[0] = gSystem->Getenv("ALIMDC_RAWDB1");
1381   if (gSystem->Getenv("ALIMDC_RAWDB2")) 
1382     rawDBFS[1] = gSystem->Getenv("ALIMDC_RAWDB2");
1383   if (gSystem->Getenv("ALIMDC_TAGDB")) 
1384     tagDBFS = gSystem->Getenv("ALIMDC_TAGDB");
1385
1386   gSystem->Exec(Form("rm -rf %s",rawDBFS[0]));
1387   gSystem->Exec(Form("rm -rf %s",rawDBFS[1]));
1388   gSystem->Exec(Form("rm -rf %s",tagDBFS));
1389
1390   gSystem->Exec(Form("mkdir %s",rawDBFS[0]));
1391   gSystem->Exec(Form("mkdir %s",rawDBFS[1]));
1392   gSystem->Exec(Form("mkdir %s",tagDBFS));
1393
1394   Int_t result = gSystem->Exec(Form("alimdc %d %d %d %d %s", 
1395                                     kDBSize, kTagDBSize, kFilter, kCompression, dateFileName));
1396   gSystem->Exec(Form("mv %s/*.root %s", rawDBFS[0], rootFileName));
1397
1398   gSystem->Exec(Form("rm -rf %s",rawDBFS[0]));
1399   gSystem->Exec(Form("rm -rf %s",rawDBFS[1]));
1400   gSystem->Exec(Form("rm -rf %s",tagDBFS));
1401
1402   return (result == 0);
1403 }
1404
1405
1406 //_____________________________________________________________________________
1407 AliRunLoader* AliSimulation::LoadRun(const char* mode) const
1408 {
1409 // delete existing run loaders, open a new one and load gAlice
1410
1411   while (AliRunLoader::GetRunLoader()) delete AliRunLoader::GetRunLoader();
1412   AliRunLoader* runLoader = 
1413     AliRunLoader::Open(fGAliceFileName.Data(), 
1414                        AliConfig::GetDefaultEventFolderName(), mode);
1415   if (!runLoader) {
1416     AliError(Form("no run loader found in file %s", fGAliceFileName.Data()));
1417     return NULL;
1418   }
1419   runLoader->LoadgAlice();
1420   runLoader->LoadHeader();
1421   gAlice = runLoader->GetAliRun();
1422   if (!gAlice) {
1423     AliError(Form("no gAlice object found in file %s", 
1424                   fGAliceFileName.Data()));
1425     return NULL;
1426   }
1427   return runLoader;
1428 }
1429
1430 //_____________________________________________________________________________
1431 Int_t AliSimulation::GetNSignalPerBkgrd(Int_t nEvents) const
1432 {
1433 // get or calculate the number of signal events per background event
1434
1435   if (!fBkgrdFileNames) return 1;
1436   Int_t nBkgrdFiles = fBkgrdFileNames->GetEntriesFast();
1437   if (nBkgrdFiles == 0) return 1;
1438
1439   // get the number of signal events
1440   if (nEvents <= 0) {
1441     AliRunLoader* runLoader = 
1442         AliRunLoader::Open(fGAliceFileName.Data(), "SIGNAL");
1443     if (!runLoader) return 1;
1444     
1445     nEvents = runLoader->GetNumberOfEvents();
1446     delete runLoader;
1447   }
1448
1449   Int_t result = 0;
1450   for (Int_t iBkgrdFile = 0; iBkgrdFile < nBkgrdFiles; iBkgrdFile++) {
1451     // get the number of background events
1452     const char* fileName = ((TObjString*)
1453                             (fBkgrdFileNames->At(iBkgrdFile)))->GetName();
1454     AliRunLoader* runLoader =
1455       AliRunLoader::Open(fileName, "BKGRD");
1456     if (!runLoader) continue;
1457     Int_t nBkgrdEvents = runLoader->GetNumberOfEvents();
1458     delete runLoader;
1459   
1460     // get or calculate the number of signal per background events
1461     Int_t nSignalPerBkgrd = fBkgrdFileNames->At(iBkgrdFile)->GetUniqueID();
1462     if (nSignalPerBkgrd <= 0) {
1463       nSignalPerBkgrd = (nEvents-1) / nBkgrdEvents + 1;
1464     } else if (result && (result != nSignalPerBkgrd)) {
1465       AliInfo(Form("the number of signal events per background event "
1466                    "will be changed from %d to %d for stream %d", 
1467                    nSignalPerBkgrd, result, iBkgrdFile+1));
1468       nSignalPerBkgrd = result;
1469     }
1470
1471     if (!result) result = nSignalPerBkgrd;
1472     if (nSignalPerBkgrd * nBkgrdEvents < nEvents) {
1473       AliWarning(Form("not enough background events (%d) for %d signal events "
1474                       "using %d signal per background events for stream %d",
1475                       nBkgrdEvents, nEvents, nSignalPerBkgrd, iBkgrdFile+1));
1476     }
1477   }
1478
1479   return result;
1480 }
1481
1482 //_____________________________________________________________________________
1483 Bool_t AliSimulation::IsSelected(TString detName, TString& detectors) const
1484 {
1485 // check whether detName is contained in detectors
1486 // if yes, it is removed from detectors
1487
1488   // check if all detectors are selected
1489   if ((detectors.CompareTo("ALL") == 0) ||
1490       detectors.BeginsWith("ALL ") ||
1491       detectors.EndsWith(" ALL") ||
1492       detectors.Contains(" ALL ")) {
1493     detectors = "ALL";
1494     return kTRUE;
1495   }
1496
1497   // search for the given detector
1498   Bool_t result = kFALSE;
1499   if ((detectors.CompareTo(detName) == 0) ||
1500       detectors.BeginsWith(detName+" ") ||
1501       detectors.EndsWith(" "+detName) ||
1502       detectors.Contains(" "+detName+" ")) {
1503     detectors.ReplaceAll(detName, "");
1504     result = kTRUE;
1505   }
1506
1507   // clean up the detectors string
1508   while (detectors.Contains("  ")) detectors.ReplaceAll("  ", " ");
1509   while (detectors.BeginsWith(" ")) detectors.Remove(0, 1);
1510   while (detectors.EndsWith(" ")) detectors.Remove(detectors.Length()-1, 1);
1511
1512   return result;
1513 }
1514
1515 //_____________________________________________________________________________
1516 Bool_t AliSimulation::ConvertRaw2SDigits(const char* rawDirectory, const char* esdFileName) 
1517 {
1518 //
1519 // Steering routine  to convert raw data in directory rawDirectory/ to fake SDigits. 
1520 // These can be used for embedding of MC tracks into RAW data using the standard 
1521 // merging procedure.
1522 //
1523 // If an ESD file is given the reconstructed vertex is taken from it and stored in the event header.
1524 //
1525     if (!gAlice) {
1526         AliError("no gAlice object. Restart aliroot and try again.");
1527         return kFALSE;
1528     }
1529     if (gAlice->Modules()->GetEntries() > 0) {
1530         AliError("gAlice was already run. Restart aliroot and try again.");
1531         return kFALSE;
1532     }
1533     
1534     AliInfo(Form("initializing gAlice with config file %s",fConfigFileName.Data()));
1535     StdoutToAliInfo(StderrToAliError(gAlice->Init(fConfigFileName.Data());););
1536 //
1537 //  Initialize CDB     
1538     InitCDB();
1539     //AliCDBManager* man = AliCDBManager::Instance();
1540     //man->SetRun(0); // Should this come from rawdata header ?
1541     
1542     Int_t iDet;
1543     //
1544     // Get the runloader
1545     AliRunLoader* runLoader = gAlice->GetRunLoader();
1546     //
1547     // Open esd file if available
1548     TFile* esdFile = TFile::Open(esdFileName);
1549     Bool_t esdOK = (esdFile != 0);
1550     AliESD* esd = new AliESD;
1551     TTree* treeESD = 0;
1552     if (esdOK) {
1553         treeESD = (TTree*) esdFile->Get("esdTree");
1554         if (!treeESD) {
1555             AliWarning("No ESD tree found");
1556             esdOK = kFALSE;
1557         } else {
1558             treeESD->SetBranchAddress("ESD", &esd);
1559         }
1560     }
1561     //
1562     // Create the RawReader
1563     TString fileName(rawDirectory);
1564     AliRawReader* rawReader = 0x0;
1565     if (fileName.EndsWith("/")) {
1566       rawReader = new AliRawReaderFile(fileName);
1567     } else if (fileName.EndsWith(".root")) {
1568       rawReader = new AliRawReaderRoot(fileName);
1569     } else if (!fileName.IsNull()) {
1570       rawReader = new AliRawReaderDate(fileName);
1571       rawReader->SelectEvents(7);
1572     }
1573 //     if (!fEquipIdMap.IsNull() && fRawReader)
1574 //       fRawReader->LoadEquipmentIdsMap(fEquipIdMap);
1575     //
1576     // Get list of detectors
1577     TObjArray* detArray = runLoader->GetAliRun()->Detectors();
1578     //
1579     // Get Header
1580     AliHeader* header = runLoader->GetHeader();
1581     //
1582     TString detStr = fMakeSDigits;
1583     // Event loop
1584     Int_t nev = 0;
1585     while(kTRUE) {
1586         if (!(rawReader->NextEvent())) break;
1587         //
1588         // Detector loop
1589         for (iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
1590             AliModule* det = (AliModule*) detArray->At(iDet);
1591             if (!det || !det->IsActive()) continue;
1592             if (IsSelected(det->GetName(), detStr)) {
1593               AliInfo(Form("Calling Raw2SDigits for %s\n", det->GetName()));
1594               det->Raw2SDigits(rawReader);
1595               rawReader->Reset();
1596             }
1597         } // detectors
1598
1599
1600         //
1601         //  If ESD information available obtain reconstructed vertex and store in header.
1602         if (esdOK) {
1603             treeESD->GetEvent(nev);
1604             const AliESDVertex* esdVertex = esd->GetPrimaryVertex();
1605             Double_t position[3];
1606             esdVertex->GetXYZ(position);
1607             AliGenEventHeader* mcHeader = new  AliGenEventHeader("ESD");
1608             TArrayF mcV;
1609             mcV.Set(3);
1610             for (Int_t i = 0; i < 3; i++) mcV[i] = position[i];
1611             mcHeader->SetPrimaryVertex(mcV);
1612             header->Reset(0,nev);
1613             header->SetGenEventHeader(mcHeader);
1614             printf("***** Saved vertex %f %f %f \n", position[0], position[1], position[2]);
1615         }
1616         nev++;
1617 //
1618 //      Finish the event
1619         runLoader->TreeE()->Fill();
1620         runLoader->SetNextEvent();
1621     } // events
1622  
1623     delete rawReader;
1624 //
1625 //  Finish the run 
1626     runLoader->CdGAFile();
1627     runLoader->WriteHeader("OVERWRITE");
1628     runLoader->WriteRunLoader();
1629
1630     return kTRUE;
1631 }
1632
1633 //_____________________________________________________________________________
1634 Int_t AliSimulation::GetDetIndex(const char* detector)
1635 {
1636   // return the detector index corresponding to detector
1637   Int_t index = -1 ; 
1638   for (index = 0; index < fgkNDetectors ; index++) {
1639     if ( strcmp(detector, fgkDetectorName[index]) == 0 )
1640           break ; 
1641   }     
1642   return index ; 
1643 }
1644
1645 //_____________________________________________________________________________
1646 Bool_t AliSimulation::RunHLT()
1647 {
1648   // Run the HLT simulation
1649   // HLT simulation is implemented in HLT/sim/AliHLTSimulation
1650   // Disabled if fRunHLT is empty, default vaule is "default".
1651   // AliSimulation::SetRunHLT can be used to set the options for HLT simulation
1652   // The default simulation depends on the HLT component libraries and their
1653   // corresponding agents which define components and chains to run. See
1654   // http://web.ift.uib.no/~kjeks/doc/alice-hlt/
1655   // http://web.ift.uib.no/~kjeks/doc/alice-hlt/classAliHLTModuleAgent.html
1656   //
1657   // The libraries to be loaded can be specified as an option.
1658   // <pre>
1659   // AliSimulation sim;
1660   // sim.SetRunHLT("libAliHLTSample.so");
1661   // </pre>
1662   // will only load <tt>libAliHLTSample.so</tt>
1663
1664   // Other available options:
1665   // \li loglevel=<i>level</i> <br>
1666   //     logging level for this processing
1667   // \li alilog=off
1668   //     disable redirection of log messages to AliLog class
1669   // \li config=<i>macro</i>
1670   //     configuration macro
1671   // \li localrec=<i>configuration</i>
1672   //     comma separated list of configurations to be run during simulation
1673
1674   int iResult=0;
1675   AliRunLoader* pRunLoader = LoadRun("READ");
1676   if (!pRunLoader) return kFALSE;
1677
1678   // initialize CDB storage, run number, set CDB lock
1679   InitCDB();
1680   if (!SetRunNumberFromData()) if (fStopOnError) return kFALSE;
1681   SetCDBLock();
1682   
1683   // load the library dynamically
1684   gSystem->Load(ALIHLTSIMULATION_LIBRARY);
1685
1686   // check for the library version
1687   AliHLTSimulationGetLibraryVersion_t fctVersion=(AliHLTSimulationGetLibraryVersion_t)(gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_GET_LIBRARY_VERSION));
1688   if (!fctVersion) {
1689     AliError(Form("can not load library %s", ALIHLTSIMULATION_LIBRARY));
1690     return kFALSE;
1691   }
1692   if (fctVersion()!= ALIHLTSIMULATION_LIBRARY_VERSION) {
1693     AliError(Form("%s version does not match: compiled for version %d, loaded %d", ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_LIBRARY_VERSION, fctVersion()));
1694     return kFALSE;
1695   }
1696
1697   // print compile info
1698   typedef void (*CompileInfo)( char*& date, char*& time);
1699   CompileInfo fctInfo=(CompileInfo)gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, "CompileInfo");
1700   if (fctInfo) {
1701     char* date="";
1702     char* time="";
1703     (*fctInfo)(date, time);
1704     if (!date) date="unknown";
1705     if (!time) time="unknown";
1706     AliInfo(Form("%s build on %s (%s)", ALIHLTSIMULATION_LIBRARY, date, time));
1707   } else {
1708     AliInfo(Form("no build info available for %s", ALIHLTSIMULATION_LIBRARY));
1709   }
1710
1711   // create instance of the HLT simulation
1712   AliHLTSimulationCreateInstance_t fctCreate=(AliHLTSimulationCreateInstance_t)(gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_CREATE_INSTANCE));
1713   AliHLTSimulation* pHLT=NULL;
1714   if (fctCreate==NULL || (pHLT=(fctCreate()))==NULL) {
1715     AliError(Form("can not create instance of HLT simulation (creator %p)", fctCreate));
1716     return kFALSE;    
1717   }
1718
1719   // init the HLT simulation
1720   TString options;
1721   if (fRunHLT.CompareTo("default")!=0) options=fRunHLT;
1722   if (!IsSelected("HLT", fWriteRawData)) {
1723     options+=" writerawfiles=";
1724   } else {
1725     options+=" writerawfiles=HLT";
1726   }
1727   AliHLTSimulationInit_t fctInit=(AliHLTSimulationInit_t)(gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_INIT));
1728   if (fctInit==NULL || (iResult=(fctInit(pHLT, pRunLoader, options.Data())))<0) {
1729     AliError(Form("can not init HLT simulation: error %d (init %p)", iResult, fctInit));
1730   } else {
1731     // run the HLT simulation
1732     AliHLTSimulationRun_t fctRun=(AliHLTSimulationRun_t)(gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_RUN));
1733     if (fctRun==NULL || (iResult=(fctRun(pHLT, pRunLoader)))<0) {
1734       AliError(Form("can not run HLT simulation: error %d (run %p)", iResult, fctRun));
1735     }
1736   }
1737
1738   // delete the instance
1739   AliHLTSimulationDeleteInstance_t fctDelete=(AliHLTSimulationDeleteInstance_t)(gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_DELETE_INSTANCE));
1740   if (fctDelete==NULL || fctDelete(pHLT)<0) {
1741     AliError(Form("can not delete instance of HLT simulation (creator %p)", fctDelete));
1742   }
1743   pHLT=NULL;
1744
1745   return iResult>=0?kTRUE:kFALSE;
1746 }
1747
1748 //_____________________________________________________________________________
1749 Bool_t AliSimulation::RunQA()
1750 {
1751         // run the QA on summable hits, digits or digits
1752
1753         AliQADataMakerSteer qas ; 
1754     qas.SetRunLoader(gAlice->GetRunLoader()) ;
1755
1756         TString detectorsw("") ;  
1757         Bool_t rv = kTRUE ; 
1758         detectorsw =  qas.Run("ALL", AliQA::kHITS) ; 
1759 //      qas.Reset() ; 
1760         detectorsw += qas.Run(fMakeSDigits.Data(), AliQA::kSDIGITS) ;   
1761 //      qas.Reset() ; 
1762         detectorsw += qas.Run(fMakeDigits.Data(), AliQA::kDIGITS) ;     
1763 //      qas.Reset() ; 
1764         detectorsw += qas.Run(fMakeDigitsFromHits.Data(), AliQA::kDIGITS) ; 
1765         
1766         if ( detectorsw.IsNull() ) 
1767                 rv = kFALSE ; 
1768         return rv ; 
1769 }
1770
1771 //_____________________________________________________________________________
1772 void AliSimulation::ProcessEnvironmentVars()
1773 {
1774 // Extract run number and random generator seed from env variables
1775
1776     AliInfo("Processing environment variables");
1777     
1778     // Random Number seed
1779     
1780     // first check that seed is not already set
1781     if (fSeed == 0) {
1782         if (gSystem->Getenv("CONFIG_SEED")) {
1783                 fSeed = atoi(gSystem->Getenv("CONFIG_SEED"));
1784         }
1785     } else {
1786         if (gSystem->Getenv("CONFIG_SEED")) {
1787                 AliInfo(Form("Seed for random number generation already set (%d)"
1788                              ": CONFIG_SEED variable ignored!", fSeed));
1789         }
1790     }
1791    
1792     AliInfo(Form("Seed for random number generation = %d ", fSeed)); 
1793
1794     // Run Number
1795     
1796     // first check that run number is not already set
1797     if(fRun < 0) {    
1798         if (gSystem->Getenv("DC_RUN")) {
1799                 fRun = atoi(gSystem->Getenv("DC_RUN"));
1800         }
1801     } else {
1802         if (gSystem->Getenv("DC_RUN")) {
1803                 AliInfo(Form("Run number already set (%d): DC_RUN variable ignored!", fRun));
1804         }
1805     }
1806     
1807     AliInfo(Form("Run number = %d", fRun)); 
1808 }
1809
1810