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