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