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