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