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