]> git.uio.no Git - u/mrichter/AliRoot.git/blob - STEER/AliReconstruction.cxx
Avoid double booking of esdfriends branch in AliReconstruction, protection in AliESDEvent
[u/mrichter/AliRoot.git] / STEER / AliReconstruction.cxx
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 the reconstruction                                      //
21 //                                                                           //
22 // Clusters and tracks are created for all detectors and all events by       //
23 // typing:                                                                   //
24 //                                                                           //
25 //   AliReconstruction rec;                                                  //
26 //   rec.Run();                                                              //
27 //                                                                           //
28 // The Run method returns kTRUE in case of successful execution.             //
29 //                                                                           //
30 // If the input to the reconstruction are not simulated digits but raw data, //
31 // this can be specified by an argument of the Run method or by the method   //
32 //                                                                           //
33 //   rec.SetInput("...");                                                    //
34 //                                                                           //
35 // The input formats and the corresponding argument are:                     //
36 // - DDL raw data files: directory name, ends with "/"                       //
37 // - raw data root file: root file name, extension ".root"                   //
38 // - raw data DATE file: DATE file name, any other non-empty string          //
39 // - MC root files     : empty string, default                               //
40 //                                                                           //
41 // By default all events are reconstructed. The reconstruction can be        //
42 // limited to a range of events by giving the index of the first and the     //
43 // last event as an argument to the Run method or by calling                 //
44 //                                                                           //
45 //   rec.SetEventRange(..., ...);                                            //
46 //                                                                           //
47 // The index -1 (default) can be used for the last event to indicate no      //
48 // upper limit of the event range.                                           //
49 //                                                                           //
50 // In case of raw-data reconstruction the user can modify the default        //
51 // number of events per digits/clusters/tracks file. In case the option      //
52 // is not used the number is set 1. In case the user provides 0, than        //
53 // the number of events is equal to the number of events inside the          //
54 // raw-data file (i.e. one digits/clusters/tracks file):                     //
55 //                                                                           //
56 //   rec.SetNumberOfEventsPerFile(...);                                      //
57 //                                                                           //
58 //                                                                           //
59 // The name of the galice file can be changed from the default               //
60 // "galice.root" by passing it as argument to the AliReconstruction          //
61 // constructor or by                                                         //
62 //                                                                           //
63 //   rec.SetGAliceFile("...");                                               //
64 //                                                                           //
65 // The local reconstruction can be switched on or off for individual         //
66 // detectors by                                                              //
67 //                                                                           //
68 //   rec.SetRunLocalReconstruction("...");                                   //
69 //                                                                           //
70 // The argument is a (case sensitive) string with the names of the           //
71 // detectors separated by a space. The special string "ALL" selects all      //
72 // available detectors. This is the default.                                 //
73 //                                                                           //
74 // The reconstruction of the primary vertex position can be switched off by  //
75 //                                                                           //
76 //   rec.SetRunVertexFinder(kFALSE);                                         //
77 //                                                                           //
78 // The tracking and the creation of ESD tracks can be switched on for        //
79 // selected detectors by                                                     //
80 //                                                                           //
81 //   rec.SetRunTracking("...");                                              //
82 //                                                                           //
83 // Uniform/nonuniform field tracking switches (default: uniform field)       //
84 //                                                                           //
85 //   rec.SetUniformFieldTracking(); ( rec.SetUniformFieldTracking(kFALSE); ) //
86 //                                                                           //
87 // The filling of additional ESD information can be steered by               //
88 //                                                                           //
89 //   rec.SetFillESD("...");                                                  //
90 //                                                                           //
91 // Again, for both methods the string specifies the list of detectors.       //
92 // The default is "ALL".                                                     //
93 //                                                                           //
94 // The call of the shortcut method                                           //
95 //                                                                           //
96 //   rec.SetRunReconstruction("...");                                        //
97 //                                                                           //
98 // is equivalent to calling SetRunLocalReconstruction, SetRunTracking and    //
99 // SetFillESD with the same detector selecting string as argument.           //
100 //                                                                           //
101 // The reconstruction requires digits or raw data as input. For the creation //
102 // of digits and raw data have a look at the class AliSimulation.            //
103 //                                                                           //
104 // The input data of a detector can be replaced by the corresponding HLT     //
105 // data by calling (usual detector string)                                   //
106 // SetUseHLTData("...");                                                     //
107 //                                                                           //
108 //                                                                           //
109 ///////////////////////////////////////////////////////////////////////////////
110
111 #include <TArrayF.h>
112 #include <TFile.h>
113 #include <TList.h>
114 #include <TSystem.h>
115 #include <TROOT.h>
116 #include <TPluginManager.h>
117 #include <TGeoManager.h>
118 #include <TLorentzVector.h>
119 #include <TArrayS.h>
120 #include <TArrayD.h>
121 #include <TObjArray.h>
122 #include <TMap.h>
123 #include <TChain.h>
124 #include <TProof.h>
125 #include <TProofOutputFile.h>
126 #include <TParameter.h>
127
128 #include "AliReconstruction.h"
129 #include "AliCodeTimer.h"
130 #include "AliReconstructor.h"
131 #include "AliLog.h"
132 #include "AliRunLoader.h"
133 #include "AliRun.h"
134 #include "AliRawReaderFile.h"
135 #include "AliRawReaderDate.h"
136 #include "AliRawReaderRoot.h"
137 #include "AliRawEventHeaderBase.h"
138 #include "AliRawEvent.h"
139 #include "AliESDEvent.h"
140 #include "AliESDMuonTrack.h"
141 #include "AliESDfriend.h"
142 #include "AliESDVertex.h"
143 #include "AliESDcascade.h"
144 #include "AliESDkink.h"
145 #include "AliESDtrack.h"
146 #include "AliESDCaloCluster.h"
147 #include "AliESDCaloCells.h"
148 #include "AliMultiplicity.h"
149 #include "AliTracker.h"
150 #include "AliVertexer.h"
151 #include "AliVertexerTracks.h"
152 #include "AliV0vertexer.h"
153 #include "AliCascadeVertexer.h"
154 #include "AliHeader.h"
155 #include "AliGenEventHeader.h"
156 #include "AliPID.h"
157 #include "AliESDpid.h"
158 #include "AliESDtrack.h"
159 #include "AliESDPmdTrack.h"
160
161 #include "AliESDTagCreator.h"
162
163 #include "AliGeomManager.h"
164 #include "AliTrackPointArray.h"
165 #include "AliCDBManager.h"
166 #include "AliCDBStorage.h"
167 #include "AliCDBEntry.h"
168 #include "AliAlignObj.h"
169
170 #include "AliCentralTrigger.h"
171 #include "AliTriggerConfiguration.h"
172 #include "AliTriggerClass.h"
173 #include "AliTriggerCluster.h"
174 #include "AliCTPRawStream.h"
175
176 #include "AliQADataMakerRec.h" 
177 #include "AliGlobalQADataMaker.h" 
178 #include "AliQA.h"
179 #include "AliQADataMakerSteer.h"
180
181 #include "AliPlaneEff.h"
182
183 #include "AliSysInfo.h" // memory snapshots
184 #include "AliRawHLTManager.h"
185
186 #include "AliMagWrapCheb.h"
187
188 #include "AliDetectorRecoParam.h"
189 #include "AliGRPRecoParam.h"
190 #include "AliRunInfo.h"
191 #include "AliEventInfo.h"
192
193 #include "AliDAQ.h"
194
195 #include "AliGRPObject.h"
196
197 ClassImp(AliReconstruction)
198
199 //_____________________________________________________________________________
200 const char* AliReconstruction::fgkDetectorName[AliReconstruction::kNDetectors] = {"ITS", "TPC", "TRD", "TOF", "PHOS", "HMPID", "EMCAL", "MUON", "FMD", "ZDC", "PMD", "T0", "VZERO", "ACORDE", "HLT"};
201
202 //_____________________________________________________________________________
203 AliReconstruction::AliReconstruction(const char* gAliceFilename) :
204   TSelector(),
205   fUniformField(kFALSE),
206   fForcedFieldMap(NULL),
207   fRunVertexFinder(kTRUE),
208   fRunVertexFinderTracks(kTRUE),
209   fRunHLTTracking(kFALSE),
210   fRunMuonTracking(kFALSE),
211   fRunV0Finder(kTRUE),
212   fRunCascadeFinder(kTRUE),
213   fStopOnError(kFALSE),
214   fWriteAlignmentData(kFALSE),
215   fWriteESDfriend(kFALSE),
216   fFillTriggerESD(kTRUE),
217
218   fCleanESD(kTRUE),
219   fV0DCAmax(3.),
220   fV0CsPmin(0.),
221   fDmax(50.),
222   fZmax(50.),
223
224   fRunLocalReconstruction("ALL"),
225   fRunTracking("ALL"),
226   fFillESD("ALL"),
227   fLoadCDB(""),
228   fUseTrackingErrorsForAlignment(""),
229   fGAliceFileName(gAliceFilename),
230   fRawInput(""),
231   fEquipIdMap(""),
232   fFirstEvent(0),
233   fLastEvent(-1),
234   fNumberOfEventsPerFile((UInt_t)-1),
235   fOptions(),
236   fLoadAlignFromCDB(kTRUE),
237   fLoadAlignData("ALL"),
238   fUseHLTData(),
239   fRunInfo(NULL),
240   fEventInfo(),
241
242   fRunLoader(NULL),
243   fRawReader(NULL),
244   fParentRawReader(NULL),
245
246   fRecoParam(),
247
248   fVertexer(NULL),
249   fDiamondProfileSPD(NULL),
250   fDiamondProfile(NULL),
251   fDiamondProfileTPC(NULL),
252   
253   fGRPData(NULL),
254
255   fAlignObjArray(NULL),
256   fCDBUri(),
257   fSpecCDBUri(), 
258   fInitCDBCalled(kFALSE),
259   fSetRunNumberFromDataCalled(kFALSE),
260   fQADetectors("ALL"), 
261   fQASteer(NULL),  
262   fQATasks("ALL"), 
263   fRunQA(kTRUE),  
264   fRunGlobalQA(kTRUE),
265   fSameQACycle(kFALSE),
266
267   fRunPlaneEff(kFALSE),
268
269   fesd(NULL),
270   fhltesd(NULL),
271   fesdf(NULL),
272   ffile(NULL),
273   ftree(NULL),
274   fhlttree(NULL),
275   ftVertexer(NULL),
276   fIsNewRunLoader(kFALSE),
277   fRunAliEVE(kFALSE),
278   fChain(NULL)
279 {
280 // create reconstruction object with default parameters
281   gGeoManager = NULL;
282   
283   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
284     fReconstructor[iDet] = NULL;
285     fLoader[iDet] = NULL;
286     fTracker[iDet] = NULL;
287   }
288   for (Int_t iDet = 0; iDet < AliQA::kNDET; iDet++) {
289     fQACycles[iDet] = 999999 ;
290     fQAWriteExpert[iDet] = kFALSE ; 
291   }
292     
293   AliPID pid;
294 }
295
296 //_____________________________________________________________________________
297 AliReconstruction::AliReconstruction(const AliReconstruction& rec) :
298   TSelector(),
299   fUniformField(rec.fUniformField),
300   fForcedFieldMap(NULL),
301   fRunVertexFinder(rec.fRunVertexFinder),
302   fRunVertexFinderTracks(rec.fRunVertexFinderTracks),
303   fRunHLTTracking(rec.fRunHLTTracking),
304   fRunMuonTracking(rec.fRunMuonTracking),
305   fRunV0Finder(rec.fRunV0Finder),
306   fRunCascadeFinder(rec.fRunCascadeFinder),
307   fStopOnError(rec.fStopOnError),
308   fWriteAlignmentData(rec.fWriteAlignmentData),
309   fWriteESDfriend(rec.fWriteESDfriend),
310   fFillTriggerESD(rec.fFillTriggerESD),
311
312   fCleanESD(rec.fCleanESD),
313   fV0DCAmax(rec.fV0DCAmax),
314   fV0CsPmin(rec.fV0CsPmin),
315   fDmax(rec.fDmax),
316   fZmax(rec.fZmax),
317
318   fRunLocalReconstruction(rec.fRunLocalReconstruction),
319   fRunTracking(rec.fRunTracking),
320   fFillESD(rec.fFillESD),
321   fLoadCDB(rec.fLoadCDB),
322   fUseTrackingErrorsForAlignment(rec.fUseTrackingErrorsForAlignment),
323   fGAliceFileName(rec.fGAliceFileName),
324   fRawInput(rec.fRawInput),
325   fEquipIdMap(rec.fEquipIdMap),
326   fFirstEvent(rec.fFirstEvent),
327   fLastEvent(rec.fLastEvent),
328   fNumberOfEventsPerFile(rec.fNumberOfEventsPerFile),
329   fOptions(),
330   fLoadAlignFromCDB(rec.fLoadAlignFromCDB),
331   fLoadAlignData(rec.fLoadAlignData),
332   fUseHLTData(rec.fUseHLTData),
333   fRunInfo(NULL),
334   fEventInfo(),
335
336   fRunLoader(NULL),
337   fRawReader(NULL),
338   fParentRawReader(NULL),
339
340   fRecoParam(rec.fRecoParam),
341
342   fVertexer(NULL),
343   fDiamondProfileSPD(rec.fDiamondProfileSPD),
344   fDiamondProfile(rec.fDiamondProfile),
345   fDiamondProfileTPC(rec.fDiamondProfileTPC),
346   
347   fGRPData(NULL),
348
349   fAlignObjArray(rec.fAlignObjArray),
350   fCDBUri(rec.fCDBUri),
351   fSpecCDBUri(), 
352   fInitCDBCalled(rec.fInitCDBCalled),
353   fSetRunNumberFromDataCalled(rec.fSetRunNumberFromDataCalled),
354   fQADetectors(rec.fQADetectors), 
355   fQASteer(NULL),  
356   fQATasks(rec.fQATasks), 
357   fRunQA(rec.fRunQA),  
358   fRunGlobalQA(rec.fRunGlobalQA),
359   fSameQACycle(rec.fSameQACycle),
360   fRunPlaneEff(rec.fRunPlaneEff),
361
362   fesd(NULL),
363   fhltesd(NULL),
364   fesdf(NULL),
365   ffile(NULL),
366   ftree(NULL),
367   fhlttree(NULL),
368   ftVertexer(NULL),
369   fIsNewRunLoader(rec.fIsNewRunLoader),
370   fRunAliEVE(kFALSE),
371   fChain(NULL)
372 {
373 // copy constructor
374
375   for (Int_t i = 0; i < rec.fOptions.GetEntriesFast(); i++) {
376     if (rec.fOptions[i]) fOptions.Add(rec.fOptions[i]->Clone());
377   }
378   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
379     fReconstructor[iDet] = NULL;
380     fLoader[iDet] = NULL;
381     fTracker[iDet] = NULL;
382   }  
383   
384   for (Int_t iDet = 0; iDet < AliQA::kNDET; iDet++) {
385     fQACycles[iDet] = rec.fQACycles[iDet];
386     fQAWriteExpert[iDet] = rec.fQAWriteExpert[iDet] ; 
387   }
388
389   for (Int_t i = 0; i < rec.fSpecCDBUri.GetEntriesFast(); i++) {
390     if (rec.fSpecCDBUri[i]) fSpecCDBUri.Add(rec.fSpecCDBUri[i]->Clone());
391   }
392 }
393
394 //_____________________________________________________________________________
395 AliReconstruction& AliReconstruction::operator = (const AliReconstruction& rec)
396 {
397 // assignment operator
398 // Used in PROOF mode
399 // Be very careful while modifing it!
400 // Simple rules to follow:
401 // for persistent data members - use their assignment operators
402 // for non-persistent ones - do nothing or take the default values from constructor
403 // TSelector members should not be touched
404   if(&rec == this) return *this;
405
406   fUniformField          = rec.fUniformField;
407   fForcedFieldMap        = NULL;
408   fRunVertexFinder       = rec.fRunVertexFinder;
409   fRunVertexFinderTracks = rec.fRunVertexFinderTracks;
410   fRunHLTTracking        = rec.fRunHLTTracking;
411   fRunMuonTracking       = rec.fRunMuonTracking;
412   fRunV0Finder           = rec.fRunV0Finder;
413   fRunCascadeFinder      = rec.fRunCascadeFinder;
414   fStopOnError           = rec.fStopOnError;
415   fWriteAlignmentData    = rec.fWriteAlignmentData;
416   fWriteESDfriend        = rec.fWriteESDfriend;
417   fFillTriggerESD        = rec.fFillTriggerESD;
418
419   fCleanESD  = rec.fCleanESD;
420   fV0DCAmax  = rec.fV0DCAmax;
421   fV0CsPmin  = rec.fV0CsPmin;
422   fDmax      = rec.fDmax;
423   fZmax      = rec.fZmax;
424
425   fRunLocalReconstruction        = rec.fRunLocalReconstruction;
426   fRunTracking                   = rec.fRunTracking;
427   fFillESD                       = rec.fFillESD;
428   fLoadCDB                       = rec.fLoadCDB;
429   fUseTrackingErrorsForAlignment = rec.fUseTrackingErrorsForAlignment;
430   fGAliceFileName                = rec.fGAliceFileName;
431   fRawInput                      = rec.fRawInput;
432   fEquipIdMap                    = rec.fEquipIdMap;
433   fFirstEvent                    = rec.fFirstEvent;
434   fLastEvent                     = rec.fLastEvent;
435   fNumberOfEventsPerFile         = rec.fNumberOfEventsPerFile;
436
437   for (Int_t i = 0; i < rec.fOptions.GetEntriesFast(); i++) {
438     if (rec.fOptions[i]) fOptions.Add(rec.fOptions[i]->Clone());
439   }
440
441   fLoadAlignFromCDB              = rec.fLoadAlignFromCDB;
442   fLoadAlignData                 = rec.fLoadAlignData;
443   fUseHLTData                    = rec.fUseHLTData;
444
445   delete fRunInfo; fRunInfo = NULL;
446   if (rec.fRunInfo) fRunInfo = new AliRunInfo(*rec.fRunInfo);
447
448   fEventInfo                     = rec.fEventInfo;
449
450   fRunLoader       = NULL;
451   fRawReader       = NULL;
452   fParentRawReader = NULL;
453
454   fRecoParam = rec.fRecoParam;
455
456   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
457     delete fReconstructor[iDet]; fReconstructor[iDet] = NULL;
458     delete fLoader[iDet]; fLoader[iDet] = NULL;
459     delete fTracker[iDet]; fTracker[iDet] = NULL;
460   }
461   
462   for (Int_t iDet = 0; iDet < AliQA::kNDET; iDet++) {
463     fQACycles[iDet] = rec.fQACycles[iDet];
464     fQAWriteExpert[iDet] = rec.fQAWriteExpert[iDet] ;
465   } 
466     
467   fVertexer             = NULL;
468   delete fDiamondProfileSPD; fDiamondProfileSPD = NULL;
469   if (rec.fDiamondProfileSPD) fDiamondProfileSPD = new AliESDVertex(*rec.fDiamondProfileSPD);
470   delete fDiamondProfile; fDiamondProfile = NULL;
471   if (rec.fDiamondProfile) fDiamondProfile = new AliESDVertex(*rec.fDiamondProfile);
472   delete fDiamondProfileTPC; fDiamondProfileTPC = NULL;
473   if (rec.fDiamondProfileTPC) fDiamondProfileTPC = new AliESDVertex(*rec.fDiamondProfileTPC);
474
475   delete fGRPData; fGRPData = NULL;
476   //  if (rec.fGRPData) fGRPData = (TMap*)((rec.fGRPData)->Clone());
477   if (rec.fGRPData) fGRPData = (AliGRPObject*)((rec.fGRPData)->Clone());
478
479   delete fAlignObjArray; fAlignObjArray = NULL;
480
481   fCDBUri        = "";
482   fSpecCDBUri.Delete();
483   fInitCDBCalled               = rec.fInitCDBCalled;
484   fSetRunNumberFromDataCalled  = rec.fSetRunNumberFromDataCalled;
485   fQADetectors                 = rec.fQADetectors;
486   fQASteer                     = NULL;  
487   fQATasks                     = rec.fQATasks; 
488   fRunQA                       = rec.fRunQA;  
489   fRunGlobalQA                 = rec.fRunGlobalQA;
490   fSameQACycle                 = rec.fSameQACycle;
491   fRunPlaneEff                 = rec.fRunPlaneEff;
492
493   fesd     = NULL;
494   fhltesd  = NULL;
495   fesdf    = NULL;
496   ffile    = NULL;
497   ftree    = NULL;
498   fhlttree = NULL;
499   ftVertexer = NULL;
500   fIsNewRunLoader = rec.fIsNewRunLoader;
501   fRunAliEVE = kFALSE;
502   fChain = NULL;
503
504   return *this;
505 }
506
507 //_____________________________________________________________________________
508 AliReconstruction::~AliReconstruction()
509 {
510 // clean up
511
512   CleanUp();
513   delete fGRPData;
514   delete fForcedFieldMap;
515   fOptions.Delete();
516   if (fAlignObjArray) {
517     fAlignObjArray->Delete();
518     delete fAlignObjArray;
519   }
520   fSpecCDBUri.Delete();
521   delete fQASteer;
522   AliCodeTimer::Instance()->Print();
523 }
524
525 //_____________________________________________________________________________
526 void AliReconstruction::InitCDB()
527 {
528 // activate a default CDB storage
529 // First check if we have any CDB storage set, because it is used 
530 // to retrieve the calibration and alignment constants
531   AliCodeTimerAuto("");
532
533   if (fInitCDBCalled) return;
534   fInitCDBCalled = kTRUE;
535
536   AliCDBManager* man = AliCDBManager::Instance();
537   if (man->IsDefaultStorageSet())
538   {
539     AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
540     AliWarning("Default CDB storage has been already set !");
541     AliWarning(Form("Ignoring the default storage declared in AliReconstruction: %s",fCDBUri.Data()));
542     AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
543     fCDBUri = man->GetDefaultStorage()->GetURI();
544   }
545   else {
546     if (fCDBUri.Length() > 0) 
547     {
548         AliDebug(2,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
549         AliDebug(2, Form("Default CDB storage is set to: %s", fCDBUri.Data()));
550         AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
551     } else {
552         fCDBUri="local://$ALICE_ROOT";
553         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
554         AliWarning("Default CDB storage not yet set !!!!");
555         AliWarning(Form("Setting it now to: %s", fCDBUri.Data()));
556         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
557                 
558     }
559     man->SetDefaultStorage(fCDBUri);
560   }
561
562   // Now activate the detector specific CDB storage locations
563   for (Int_t i = 0; i < fSpecCDBUri.GetEntriesFast(); i++) {
564     TObject* obj = fSpecCDBUri[i];
565     if (!obj) continue;
566     AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
567     AliDebug(2, Form("Specific CDB storage for %s is set to: %s",obj->GetName(),obj->GetTitle()));
568     AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
569     man->SetSpecificStorage(obj->GetName(), obj->GetTitle());
570   }
571   AliSysInfo::AddStamp("InitCDB");
572 }
573
574 //_____________________________________________________________________________
575 void AliReconstruction::SetDefaultStorage(const char* uri) {
576 // Store the desired default CDB storage location
577 // Activate it later within the Run() method
578
579   fCDBUri = uri;
580
581 }
582
583 //_____________________________________________________________________________
584 void AliReconstruction::SetSpecificStorage(const char* calibType, const char* uri) {
585 // Store a detector-specific CDB storage location
586 // Activate it later within the Run() method
587
588   AliCDBPath aPath(calibType);
589   if(!aPath.IsValid()){
590         // if calibType is not wildcard but it is a valid detector, add "/*" to make it a valid path
591         for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
592                 if(!strcmp(calibType, fgkDetectorName[iDet])) {
593                         aPath.SetPath(Form("%s/*", calibType));
594                         AliInfo(Form("Path for specific storage set to %s", aPath.GetPath().Data()));
595                         break;
596                 }
597         }
598         if(!aPath.IsValid()){
599                 AliError(Form("Not a valid path or detector: %s", calibType));
600                 return;
601         }
602   }
603
604 //  // check that calibType refers to a "valid" detector name
605 //  Bool_t isDetector = kFALSE;
606 //  for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
607 //    TString detName = fgkDetectorName[iDet];
608 //    if(aPath.GetLevel0() == detName) {
609 //      isDetector = kTRUE;
610 //      break;
611 //    }
612 //  }
613 //
614 //  if(!isDetector) {
615 //      AliError(Form("Not a valid detector: %s", aPath.GetLevel0().Data()));
616 //      return;
617 //  }
618
619   TObject* obj = fSpecCDBUri.FindObject(aPath.GetPath().Data());
620   if (obj) fSpecCDBUri.Remove(obj);
621   fSpecCDBUri.Add(new TNamed(aPath.GetPath().Data(), uri));
622
623 }
624
625 //_____________________________________________________________________________
626 Bool_t AliReconstruction::SetRunNumberFromData()
627 {
628   // The method is called in Run() in order
629   // to set a correct run number.
630   // In case of raw data reconstruction the
631   // run number is taken from the raw data header
632
633   if (fSetRunNumberFromDataCalled) return kTRUE;
634   fSetRunNumberFromDataCalled = kTRUE;
635   
636   AliCDBManager* man = AliCDBManager::Instance();
637  
638   if(fRawReader) {
639     if(fRawReader->NextEvent()) {
640       if(man->GetRun() > 0) {
641         AliWarning("Run number is taken from raw-event header! Ignoring settings in AliCDBManager!");
642       } 
643       man->SetRun(fRawReader->GetRunNumber());
644       fRawReader->RewindEvents();
645     }
646     else {
647       if(man->GetRun() > 0) {
648         AliWarning("No raw-data events are found ! Using settings in AliCDBManager !");
649       }
650       else {
651         AliWarning("Neither raw events nor settings in AliCDBManager are found !");
652         return kFALSE;
653       }
654     }
655   }
656   else {
657     AliRunLoader *rl = AliRunLoader::Open(fGAliceFileName.Data());
658     if (!rl) {
659       AliError(Form("No run loader found in file %s", fGAliceFileName.Data()));
660       return kFALSE;
661     }
662     else {
663       rl->LoadHeader();
664       // read run number from gAlice
665       if(rl->GetHeader()) {
666         man->SetRun(rl->GetHeader()->GetRun());
667         rl->UnloadHeader();
668         delete rl;
669       }
670       else {
671         AliError("Neither run-loader header nor RawReader objects are found !");
672         delete rl;
673         return kFALSE;
674       }
675     }
676   }
677
678   man->Print();  
679   
680   return kTRUE;
681 }
682
683 //_____________________________________________________________________________
684 void AliReconstruction::SetCDBLock() {
685   // Set CDB lock: from now on it is forbidden to reset the run number
686   // or the default storage or to activate any further storage!
687   
688   AliCDBManager::Instance()->SetLock(1);
689 }
690
691 //_____________________________________________________________________________
692 Bool_t AliReconstruction::MisalignGeometry(const TString& detectors)
693 {
694   // Read the alignment objects from CDB.
695   // Each detector is supposed to have the
696   // alignment objects in DET/Align/Data CDB path.
697   // All the detector objects are then collected,
698   // sorted by geometry level (starting from ALIC) and
699   // then applied to the TGeo geometry.
700   // Finally an overlaps check is performed.
701
702   // Load alignment data from CDB and fill fAlignObjArray 
703   if(fLoadAlignFromCDB){
704         
705     TString detStr = detectors;
706     TString loadAlObjsListOfDets = "";
707     
708     for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
709       if(!IsSelected(fgkDetectorName[iDet], detStr)) continue;
710       if(!strcmp(fgkDetectorName[iDet],"HLT")) continue;
711       
712       if(AliGeomManager::GetNalignable(fgkDetectorName[iDet]) != 0)
713       {
714         loadAlObjsListOfDets += fgkDetectorName[iDet];
715         loadAlObjsListOfDets += " ";
716       }
717     } // end loop over detectors
718     
719     if(AliGeomManager::GetNalignable("GRP") != 0)
720       loadAlObjsListOfDets.Prepend("GRP "); //add alignment objects for non-sensitive modules
721     AliGeomManager::ApplyAlignObjsFromCDB(loadAlObjsListOfDets.Data());
722     AliCDBManager::Instance()->UnloadFromCache("*/Align/*");
723   }else{
724     // Check if the array with alignment objects was
725     // provided by the user. If yes, apply the objects
726     // to the present TGeo geometry
727     if (fAlignObjArray) {
728       if (gGeoManager && gGeoManager->IsClosed()) {
729         if (AliGeomManager::ApplyAlignObjsToGeom(*fAlignObjArray) == kFALSE) {
730           AliError("The misalignment of one or more volumes failed!"
731                    "Compare the list of simulated detectors and the list of detector alignment data!");
732           return kFALSE;
733         }
734       }
735       else {
736         AliError("Can't apply the misalignment! gGeoManager doesn't exist or it is still opened!");
737         return kFALSE;
738       }
739     }
740   }
741   
742   if (fAlignObjArray) {
743     fAlignObjArray->Delete();
744     delete fAlignObjArray; fAlignObjArray=NULL;
745   }
746
747   return kTRUE;
748 }
749
750 //_____________________________________________________________________________
751 void AliReconstruction::SetGAliceFile(const char* fileName)
752 {
753 // set the name of the galice file
754
755   fGAliceFileName = fileName;
756 }
757
758 //_____________________________________________________________________________
759 void AliReconstruction::SetInput(const char* input) 
760 {
761   // In case the input string starts with 'mem://', we run in an online mode
762   // and AliRawReaderDateOnline object is created. In all other cases a raw-data
763   // file is assumed. One can give as an input:
764   // mem://: - events taken from DAQ monitoring libs online
765   //  or
766   // mem://<filename> - emulation of the above mode (via DATE monitoring libs)
767   if (input) fRawInput = input;
768 }
769
770 //_____________________________________________________________________________
771 void AliReconstruction::SetOption(const char* detector, const char* option)
772 {
773 // set options for the reconstruction of a detector
774
775   TObject* obj = fOptions.FindObject(detector);
776   if (obj) fOptions.Remove(obj);
777   fOptions.Add(new TNamed(detector, option));
778 }
779
780 //_____________________________________________________________________________
781 void AliReconstruction::SetRecoParam(const char* detector, AliDetectorRecoParam *par)
782 {
783   // Set custom reconstruction parameters for a given detector
784   // Single set of parameters for all the events
785
786   // First check if the reco-params are global
787   if(!strcmp(detector, "GRP")) {
788     par->SetAsDefault();
789     fRecoParam.AddDetRecoParam(kNDetectors,par);
790     return;
791   }
792
793   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
794     if(!strcmp(detector, fgkDetectorName[iDet])) {
795       par->SetAsDefault();
796       fRecoParam.AddDetRecoParam(iDet,par);
797       break;
798     }
799   }
800
801 }
802
803 //_____________________________________________________________________________
804 Bool_t AliReconstruction::SetFieldMap(Float_t l3Current, Float_t diCurrent, Float_t factor, const char *path) {
805   //------------------------------------------------
806   // The magnetic field map, defined externally...
807   // L3 current 30000 A  -> 0.5 T
808   // L3 current 12000 A  -> 0.2 T
809   // dipole current 6000 A
810   // The polarities must be the same
811   //------------------------------------------------
812   const Float_t l3NominalCurrent1=30000.; // (A)
813   const Float_t l3NominalCurrent2=12000.; // (A)
814   const Float_t diNominalCurrent =6000. ; // (A)
815
816   const Float_t tolerance=0.03; // relative current tolerance
817   const Float_t zero=77.;       // "zero" current (A)
818
819   Int_t map=0;
820   Bool_t dipoleON=kFALSE;
821
822   TString s=(factor < 0) ? "L3: -" : "L3: +";
823
824   l3Current = TMath::Abs(l3Current);
825   if (TMath::Abs(l3Current-l3NominalCurrent1)/l3NominalCurrent1 < tolerance) {
826     map=AliMagWrapCheb::k5kG;
827     s+="0.5 T;  ";
828   } else
829   if (TMath::Abs(l3Current-l3NominalCurrent2)/l3NominalCurrent2 < tolerance) {
830     map=AliMagWrapCheb::k2kG;
831     s+="0.2 T;  ";
832   } else
833   if (l3Current < zero) {
834     map=AliMagWrapCheb::k2kG;
835     s+="0.0 T;  ";
836     factor=0.;                  // in fact, this is a global factor...
837     fUniformField=kTRUE;        // track with the uniform (zero) B field
838   } else {
839     AliError(Form("Wrong L3 current (%f A)!",l3Current));
840     return kFALSE;
841   }
842
843   diCurrent = TMath::Abs(diCurrent);
844   if (TMath::Abs(diCurrent-diNominalCurrent)/diNominalCurrent < tolerance) {
845     // 3% current tolerance...
846     dipoleON=kTRUE;
847     s+="Dipole ON";
848   } else
849   if (diCurrent < zero) { // some small current..
850     dipoleON=kFALSE;
851     s+="Dipole OFF";
852   } else {
853     AliError(Form("Wrong dipole current (%f A)!",diCurrent));
854     return kFALSE;
855   }
856
857   delete fForcedFieldMap;
858   fForcedFieldMap=
859     new AliMagWrapCheb("B field map  ",s,2,factor,10.,map,dipoleON,path);
860
861   fForcedFieldMap->Print();
862
863   AliTracker::SetFieldMap(fForcedFieldMap,fUniformField);    
864
865   return kTRUE;
866 }
867
868
869 Bool_t AliReconstruction::InitGRP() {
870   //------------------------------------
871   // Initialization of the GRP entry 
872   //------------------------------------
873   AliCDBEntry* entry = AliCDBManager::Instance()->Get("GRP/GRP/Data");
874
875   if (entry) {
876
877     TMap* m = dynamic_cast<TMap*>(entry->GetObject());  // old GRP entry
878
879     if (m) {
880        AliInfo("Found a TMap in GRP/GRP/Data, converting it into an AliGRPObject");
881        m->Print();
882        fGRPData = new AliGRPObject();
883        fGRPData->ReadValuesFromMap(m);
884     }
885
886     else {
887        AliInfo("Found an AliGRPObject in GRP/GRP/Data, reading it");
888        fGRPData = dynamic_cast<AliGRPObject*>(entry->GetObject());  // new GRP entry
889        entry->SetOwner(0);
890     }
891
892     AliCDBManager::Instance()->UnloadFromCache("GRP/GRP/Data");
893   }
894
895   if (!fGRPData) {
896      AliError("No GRP entry found in OCDB!");
897      return kFALSE;
898   }
899
900   TString lhcState = fGRPData->GetLHCState();
901   if (lhcState==AliGRPObject::GetInvalidString()) {
902     AliError("GRP/GRP/Data entry:  missing value for the LHC state ! Using UNKNOWN");
903     lhcState = "UNKNOWN";
904   }
905
906   TString beamType = fGRPData->GetBeamType();
907   if (beamType==AliGRPObject::GetInvalidString()) {
908     AliError("GRP/GRP/Data entry:  missing value for the beam type ! Using UNKNOWN");
909     beamType = "UNKNOWN";
910   }
911
912   Float_t beamEnergy = fGRPData->GetBeamEnergy();
913   if (beamEnergy==AliGRPObject::GetInvalidFloat()) {
914     AliError("GRP/GRP/Data entry:  missing value for the beam energy ! Using 0");
915     beamEnergy = 0;
916   }
917
918   TString runType = fGRPData->GetRunType();
919   if (runType==AliGRPObject::GetInvalidString()) {
920     AliError("GRP/GRP/Data entry:  missing value for the run type ! Using UNKNOWN");
921     runType = "UNKNOWN";
922   }
923
924   Int_t activeDetectors = fGRPData->GetDetectorMask();
925   if (activeDetectors==AliGRPObject::GetInvalidUInt()) {
926     AliError("GRP/GRP/Data entry:  missing value for the detector mask ! Using 1074790399");
927     activeDetectors = 1074790399;
928   }
929
930   fRunInfo = new AliRunInfo(lhcState, beamType, beamEnergy, runType, activeDetectors);
931
932   fRunInfo->Dump();
933
934
935   // Process the list of active detectors
936   if (activeDetectors) {
937     UInt_t detMask = activeDetectors;
938     fRunLocalReconstruction = MatchDetectorList(fRunLocalReconstruction,detMask);
939     fRunTracking = MatchDetectorList(fRunTracking,detMask);
940     fFillESD = MatchDetectorList(fFillESD,detMask);
941     fQADetectors = MatchDetectorList(fQADetectors,detMask);
942     fLoadCDB.Form("%s %s %s %s",
943                   fRunLocalReconstruction.Data(),
944                   fRunTracking.Data(),
945                   fFillESD.Data(),
946                   fQADetectors.Data());
947     fLoadCDB = MatchDetectorList(fLoadCDB,detMask);
948     if (!((detMask >> AliDAQ::DetectorID("ITSSPD")) & 0x1)) {
949       // switch off the vertexer
950       AliInfo("SPD is not in the list of active detectors. Vertexer switched off.");
951       fRunVertexFinder = kFALSE;
952     }
953     if (!((detMask >> AliDAQ::DetectorID("TRG")) & 0x1)) {
954       // switch off the reading of CTP raw-data payload
955       if (fFillTriggerESD) {
956         AliInfo("CTP is not in the list of active detectors. CTP data reading switched off.");
957         fFillTriggerESD = kFALSE;
958       }
959     }
960   }
961
962   AliInfo("===================================================================================");
963   AliInfo(Form("Running local reconstruction for detectors: %s",fRunLocalReconstruction.Data()));
964   AliInfo(Form("Running tracking for detectors: %s",fRunTracking.Data()));
965   AliInfo(Form("Filling ESD for detectors: %s",fFillESD.Data()));
966   AliInfo(Form("Quality assurance is active for detectors: %s",fQADetectors.Data()));
967   AliInfo(Form("CDB and reconstruction parameters are loaded for detectors: %s",fLoadCDB.Data()));
968   AliInfo("===================================================================================");
969
970   //*** Dealing with the magnetic field map
971   if (AliTracker::GetFieldMap()) {
972     AliInfo("Running with the externally set B field !");
973   } else {
974     // Construct the field map out of the information retrieved from GRP.
975
976     Bool_t ok = kTRUE;
977
978     // L3
979     Float_t l3Current = fGRPData->GetL3Current((AliGRPObject::Stats)0);
980     if (l3Current == AliGRPObject::GetInvalidFloat()) {
981       AliError("GRP/GRP/Data entry:  missing value for the L3 current !");
982       ok = kFALSE;
983     }
984
985     Char_t l3Polarity = fGRPData->GetL3Polarity();
986     if (l3Polarity == AliGRPObject::GetInvalidChar()) {
987       AliError("GRP/GRP/Data entry:  missing value for the L3 polarity !");
988       ok = kFALSE;
989     }
990
991     // Dipole
992     Float_t diCurrent = fGRPData->GetDipoleCurrent((AliGRPObject::Stats)0);
993     if (diCurrent == AliGRPObject::GetInvalidFloat()) {
994       AliError("GRP/GRP/Data entry:  missing value for the dipole current !");
995       ok = kFALSE;
996     }
997
998     Char_t diPolarity = fGRPData->GetDipolePolarity();
999     if (diPolarity == AliGRPObject::GetInvalidChar()) {
1000       AliError("GRP/GRP/Data entry:  missing value for the dipole polarity !");
1001       ok = kFALSE;
1002     }
1003
1004     /*
1005     TObjString *l3Current=
1006        dynamic_cast<TObjString*>(fGRPData->GetValue("fL3Current"));
1007     if (!l3Current) {
1008       AliError("GRP/GRP/Data entry:  missing value for the L3 current !");
1009       ok = kFALSE;
1010     }
1011     TObjString *l3Polarity=
1012        dynamic_cast<TObjString*>(fGRPData->GetValue("fL3Polarity"));
1013     if (!l3Polarity) {
1014       AliError("GRP/GRP/Data entry:  missing value for the L3 polarity !");
1015       ok = kFALSE;
1016     }
1017     
1018     // Dipole
1019     TObjString *diCurrent=
1020        dynamic_cast<TObjString*>(fGRPData->GetValue("fDipoleCurrent"));
1021     if (!diCurrent) {
1022       AliError("GRP/GRP/Data entry:  missing value for the dipole current !");
1023       ok = kFALSE;
1024     }
1025     TObjString *diPolarity=
1026        dynamic_cast<TObjString*>(fGRPData->GetValue("fDipolePolarity"));
1027     if (!diPolarity) {
1028       AliError("GRP/GRP/Data entry:  missing value for the dipole polarity !");
1029       ok = kFALSE;
1030     }
1031     */
1032
1033     if (ok) { 
1034        Float_t l3Cur=TMath::Abs(l3Current);
1035        Float_t diCur=TMath::Abs(diCurrent);
1036        Float_t l3Pol=l3Polarity;
1037        //       Float_t l3Cur=TMath::Abs(atof(l3Current->GetName()));
1038        //Float_t diCur=TMath::Abs(atof(diCurrent->GetName()));
1039        //Float_t l3Pol=atof(l3Polarity->GetName());
1040        Float_t factor=1.;
1041        if (l3Pol != 0.) factor=-1.;
1042     
1043
1044       if (!SetFieldMap(l3Cur, diCur, factor)) {
1045          AliFatal("Failed to creat a B field map ! Exiting...");
1046       }
1047       AliInfo("Running with the B field constructed out of GRP !");
1048     }
1049     else {
1050       AliFatal("B field is neither set nor constructed from GRP ! Exitig...");
1051     }
1052
1053   }
1054
1055   //*** Get the diamond profiles from OCDB
1056   entry = AliCDBManager::Instance()->Get("GRP/Calib/MeanVertexSPD");
1057   if (entry) {
1058     fDiamondProfileSPD = dynamic_cast<AliESDVertex*> (entry->GetObject());  
1059   } else {
1060      AliError("No SPD diamond profile found in OCDB!");
1061   }
1062
1063   entry = AliCDBManager::Instance()->Get("GRP/Calib/MeanVertex");
1064   if (entry) {
1065     fDiamondProfile = dynamic_cast<AliESDVertex*> (entry->GetObject());  
1066   } else {
1067      AliError("No diamond profile found in OCDB!");
1068   }
1069
1070   entry = AliCDBManager::Instance()->Get("GRP/Calib/MeanVertexTPC");
1071   if (entry) {
1072     fDiamondProfileTPC = dynamic_cast<AliESDVertex*> (entry->GetObject());  
1073   } else {
1074      AliError("No TPC diamond profile found in OCDB!");
1075   }
1076
1077   return kTRUE;
1078
1079
1080 //_____________________________________________________________________________
1081 Bool_t AliReconstruction::LoadCDB()
1082 {
1083   AliCodeTimerAuto("");
1084
1085   AliCDBManager::Instance()->Get("GRP/CTP/Config");
1086
1087   TString detStr = fLoadCDB;
1088   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
1089     if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
1090     AliCDBManager::Instance()->GetAll(Form("%s/Calib/*",fgkDetectorName[iDet]));
1091   }
1092   return kTRUE;
1093 }
1094
1095 //_____________________________________________________________________________
1096 Bool_t AliReconstruction::Run(const char* input)
1097 {
1098   // Run Run Run
1099   AliCodeTimerAuto("");
1100
1101   InitRun(input);
1102   if (GetAbort() != TSelector::kContinue) return kFALSE;
1103
1104   TChain *chain = NULL;
1105   if (fRawReader && (chain = fRawReader->GetChain())) {
1106     // Proof mode
1107     if (gProof) {
1108       gProof->AddInput(this);
1109       TUrl outputFile;
1110       outputFile.SetProtocol("root",kTRUE);
1111       outputFile.SetHost(gSystem->HostName());
1112       outputFile.SetFile(Form("%s/AliESDs.root",gSystem->pwd()));
1113       AliInfo(Form("Output file with ESDs is %s",outputFile.GetUrl()));
1114       gProof->AddInput(new TNamed("PROOF_OUTPUTFILE",outputFile.GetUrl()));
1115       chain->SetProof();
1116       chain->Process("AliReconstruction");
1117     }
1118     else {
1119       chain->Process(this);
1120     }
1121   }
1122   else {
1123     Begin(NULL);
1124     if (GetAbort() != TSelector::kContinue) return kFALSE;
1125     SlaveBegin(NULL);
1126     if (GetAbort() != TSelector::kContinue) return kFALSE;
1127     //******* The loop over events
1128     AliInfo("Starting looping over events");
1129     Int_t iEvent = 0;
1130     while ((iEvent < fRunLoader->GetNumberOfEvents()) ||
1131            (fRawReader && fRawReader->NextEvent())) {
1132       if (!ProcessEvent(iEvent)) {
1133         Abort("ProcessEvent",TSelector::kAbortFile);
1134         return kFALSE;
1135       }
1136       iEvent++;
1137     }
1138     SlaveTerminate();
1139     if (GetAbort() != TSelector::kContinue) return kFALSE;
1140     Terminate();
1141     if (GetAbort() != TSelector::kContinue) return kFALSE;
1142   }
1143
1144   return kTRUE;
1145 }
1146
1147 //_____________________________________________________________________________
1148 void AliReconstruction::InitRawReader(const char* input)
1149 {
1150   AliCodeTimerAuto("");
1151
1152   // Init raw-reader and
1153   // set the input in case of raw data
1154   if (input) fRawInput = input;
1155   fRawReader = AliRawReader::Create(fRawInput.Data());
1156   if (!fRawReader)
1157     AliInfo("Reconstruction will run over digits");
1158
1159   if (!fEquipIdMap.IsNull() && fRawReader)
1160     fRawReader->LoadEquipmentIdsMap(fEquipIdMap);
1161
1162   if (!fUseHLTData.IsNull()) {
1163     // create the RawReaderHLT which performs redirection of HLT input data for
1164     // the specified detectors
1165     AliRawReader* pRawReader=AliRawHLTManager::CreateRawReaderHLT(fRawReader, fUseHLTData.Data());
1166     if (pRawReader) {
1167       fParentRawReader=fRawReader;
1168       fRawReader=pRawReader;
1169     } else {
1170       AliError(Form("can not create Raw Reader for HLT input %s", fUseHLTData.Data()));
1171     }
1172   }
1173   AliSysInfo::AddStamp("CreateRawReader");
1174 }
1175
1176 //_____________________________________________________________________________
1177 void AliReconstruction::InitRun(const char* input)
1178 {
1179   // Initialization of raw-reader,
1180   // run number, CDB etc.
1181   AliCodeTimerAuto("");
1182   AliSysInfo::AddStamp("Start");
1183
1184   // Initialize raw-reader if any
1185   InitRawReader(input);
1186
1187   // Initialize the CDB storage
1188   InitCDB();
1189
1190   // Set run number in CDBManager (if it is not already set by the user)
1191   if (!SetRunNumberFromData()) {
1192     Abort("SetRunNumberFromData", TSelector::kAbortProcess);
1193     return;
1194   }
1195
1196   // Set CDB lock: from now on it is forbidden to reset the run number
1197   // or the default storage or to activate any further storage!
1198   SetCDBLock();
1199   
1200 }
1201
1202 //_____________________________________________________________________________
1203 void AliReconstruction::Begin(TTree *)
1204 {
1205   // Initialize AlReconstruction before
1206   // going into the event loop
1207   // Should follow the TSelector convention
1208   // i.e. initialize only the object on the client side
1209   AliCodeTimerAuto("");
1210
1211   AliReconstruction *reco = NULL;
1212   if (fInput) {
1213     if ((reco = (AliReconstruction*)fInput->FindObject("AliReconstruction"))) {
1214       *this = *reco;
1215     }
1216     AliSysInfo::AddStamp("ReadInputInBegin");
1217   }
1218
1219   // Import ideal TGeo geometry and apply misalignment
1220   if (!gGeoManager) {
1221     TString geom(gSystem->DirName(fGAliceFileName));
1222     geom += "/geometry.root";
1223     AliGeomManager::LoadGeometry(geom.Data());
1224     if (!gGeoManager) {
1225       Abort("LoadGeometry", TSelector::kAbortProcess);
1226       return;
1227     }
1228     AliSysInfo::AddStamp("LoadGeom");
1229     TString detsToCheck=fRunLocalReconstruction;
1230     if(!AliGeomManager::CheckSymNamesLUT(detsToCheck.Data())) {
1231       Abort("CheckSymNamesLUT", TSelector::kAbortProcess);
1232       return;
1233     }
1234     AliSysInfo::AddStamp("CheckGeom");
1235   }
1236
1237   if (!MisalignGeometry(fLoadAlignData)) {
1238     Abort("MisalignGeometry", TSelector::kAbortProcess);
1239     return;
1240   }
1241   AliCDBManager::Instance()->UnloadFromCache("GRP/Geometry/Data");
1242   AliSysInfo::AddStamp("MisalignGeom");
1243
1244   if (!InitGRP()) {
1245     Abort("InitGRP", TSelector::kAbortProcess);
1246     return;
1247   }
1248   AliSysInfo::AddStamp("InitGRP");
1249
1250   if (!LoadCDB()) {
1251     Abort("LoadCDB", TSelector::kAbortProcess);
1252     return;
1253   }
1254   AliSysInfo::AddStamp("LoadCDB");
1255
1256   // Read the reconstruction parameters from OCDB
1257   if (!InitRecoParams()) {
1258     AliWarning("Not all detectors have correct RecoParam objects initialized");
1259   }
1260   AliSysInfo::AddStamp("InitRecoParams");
1261
1262   if (fInput) {
1263     if (reco) *reco = *this;
1264     fInput->Add(gGeoManager);
1265     gGeoManager = NULL;
1266     fInput->Add(const_cast<TMap*>(AliCDBManager::Instance()->GetEntryCache()));
1267     fInput->Add(new TParameter<Int_t>("RunNumber",AliCDBManager::Instance()->GetRun()));
1268     AliMagF *magFieldMap = (AliMagF*)AliTracker::GetFieldMap();
1269     magFieldMap->SetName("MagneticFieldMap");
1270     fInput->Add(magFieldMap);
1271   }
1272
1273 }
1274
1275 //_____________________________________________________________________________
1276 void AliReconstruction::SlaveBegin(TTree*)
1277 {
1278   // Initialization related to run-loader,
1279   // vertexer, trackers, recontructors
1280   // In proof mode it is executed on the slave
1281   AliCodeTimerAuto("");
1282
1283   TProofOutputFile *outProofFile = NULL;
1284   if (fInput) { 
1285     if (AliReconstruction *reco = (AliReconstruction*)fInput->FindObject("AliReconstruction")) {
1286       *this = *reco;
1287     }
1288     if (TGeoManager *tgeo = (TGeoManager*)fInput->FindObject("Geometry")) {
1289       gGeoManager = tgeo;
1290       AliGeomManager::SetGeometry(tgeo);
1291     }
1292     if (TMap *entryCache = (TMap*)fInput->FindObject("CDBEntryCache")) {
1293       Int_t runNumber = -1;
1294       if (TProof::GetParameter(fInput,"RunNumber",runNumber) == 0) {
1295         AliCDBManager *man = AliCDBManager::Instance(entryCache,runNumber);
1296         man->SetCacheFlag(kTRUE);
1297         man->SetLock(kTRUE);
1298         man->Print();
1299       }
1300     }
1301     if (AliMagF *map = (AliMagF*)fInput->FindObject("MagneticFieldMap")) {
1302       AliTracker::SetFieldMap(map,fUniformField);
1303     }
1304     if (TNamed *outputFileName = (TNamed *) fInput->FindObject("PROOF_OUTPUTFILE")) {
1305       outProofFile = new TProofOutputFile(gSystem->BaseName(TUrl(outputFileName->GetTitle()).GetFile()));
1306       outProofFile->SetOutputFileName(outputFileName->GetTitle());
1307       fOutput->Add(outProofFile);
1308     }
1309     AliSysInfo::AddStamp("ReadInputInSlaveBegin");
1310   }
1311
1312   // get the run loader
1313   if (!InitRunLoader()) {
1314     Abort("InitRunLoader", TSelector::kAbortProcess);
1315     return;
1316   }
1317   AliSysInfo::AddStamp("LoadLoader");
1318  
1319   ftVertexer = new AliVertexerTracks(AliTracker::GetBz());
1320
1321   // get vertexer
1322   if (fRunVertexFinder && !CreateVertexer()) {
1323     Abort("CreateVertexer", TSelector::kAbortProcess);
1324     return;
1325   }
1326   AliSysInfo::AddStamp("CreateVertexer");
1327
1328   // get trackers
1329   if (!fRunTracking.IsNull() && !CreateTrackers(fRunTracking)) {
1330     Abort("CreateTrackers", TSelector::kAbortProcess);
1331     return;
1332   }      
1333   AliSysInfo::AddStamp("CreateTrackers");
1334
1335   // create the ESD output file and tree
1336   if (!outProofFile) {
1337     ffile = TFile::Open("AliESDs.root", "RECREATE");
1338     ffile->SetCompressionLevel(2);
1339     if (!ffile->IsOpen()) {
1340       Abort("OpenESDFile", TSelector::kAbortProcess);
1341       return;
1342     }
1343   }
1344   else {
1345     if (!(ffile = outProofFile->OpenFile("RECREATE"))) {
1346       Abort(Form("Problems opening output PROOF file: %s/%s",
1347                  outProofFile->GetDir(), outProofFile->GetFileName()),
1348             TSelector::kAbortProcess);
1349       return;
1350     }
1351   }
1352
1353   ftree = new TTree("esdTree", "Tree with ESD objects");
1354   fesd = new AliESDEvent();
1355   fesd->CreateStdContent();
1356
1357   fesd->WriteToTree(ftree);
1358   if (fWriteESDfriend) {
1359     // careful:
1360     // Since we add the branch manually we must 
1361     // book and add it after WriteToTree
1362     // otherwise it is created twice,
1363     // once via writetotree and once here.
1364     // The case for AliESDfriend is now 
1365     // caught also in AlIESDEvent::WriteToTree but 
1366     // be careful when changing the name (AliESDfriend is not 
1367     // a TNamed so we had to hardwire it)
1368     fesdf = new AliESDfriend();
1369     TBranch *br=ftree->Branch("ESDfriend.","AliESDfriend", &fesdf);
1370     br->SetFile("AliESDfriends.root");
1371     fesd->AddObject(fesdf);
1372   }
1373   ftree->GetUserInfo()->Add(fesd);
1374
1375   fhlttree = new TTree("HLTesdTree", "Tree with HLT ESD objects");
1376   fhltesd = new AliESDEvent();
1377   fhltesd->CreateStdContent();
1378
1379   // read the ESD template from CDB
1380   // HLT is allowed to put non-std content to its ESD, the non-std
1381   // objects need to be created before invocation of WriteToTree in
1382   // order to create all branches. Initialization is done from an
1383   // ESD layout template in CDB
1384   AliCDBManager* man = AliCDBManager::Instance();
1385   AliCDBPath hltESDConfigPath("HLT/ConfigHLT/esdLayout");
1386   AliCDBEntry* hltESDConfig=NULL;
1387   if (man->GetId(hltESDConfigPath)!=NULL &&
1388       (hltESDConfig=man->Get(hltESDConfigPath))!=NULL) {
1389     AliESDEvent* pESDLayout=dynamic_cast<AliESDEvent*>(hltESDConfig->GetObject());
1390     if (pESDLayout) {
1391       // init all internal variables from the list of objects
1392       pESDLayout->GetStdContent();
1393
1394       // copy content and create non-std objects
1395       *fhltesd=*pESDLayout;
1396       fhltesd->Reset();
1397     } else {
1398       AliError(Form("error setting hltEsd layout from %s: invalid object type",
1399                     hltESDConfigPath.GetPath().Data()));
1400     }
1401   }
1402
1403   fhltesd->WriteToTree(fhlttree);
1404   fhlttree->GetUserInfo()->Add(fhltesd);
1405
1406   ProcInfo_t procInfo;
1407   gSystem->GetProcInfo(&procInfo);
1408   AliInfo(Form("Current memory usage %d %d", procInfo.fMemResident, procInfo.fMemVirtual));
1409   
1410   //QA
1411   //Initialize the QA and start of cycle 
1412   if (fRunQA) {
1413     fQASteer = new AliQADataMakerSteer("rec") ; 
1414     fQASteer->SetActiveDetectors(fQADetectors) ; 
1415     for (Int_t det = 0 ; det < AliQA::kNDET ; det++) {
1416       fQASteer->SetCycleLength(AliQA::DETECTORINDEX_t(det), fQACycles[det]) ;  
1417       if (fQAWriteExpert[det])
1418         fQASteer->SetWriteExpert(AliQA::DETECTORINDEX_t(det)) ;
1419     }
1420     
1421     if (!fRawReader && fQATasks.Contains(AliQA::kRAWS))
1422       fQATasks.ReplaceAll(Form("%d",AliQA::kRAWS), "") ;
1423     fQASteer->SetTasks(fQATasks) ; 
1424     fQASteer->InitQADataMaker(AliCDBManager::Instance()->GetRun(), fRecoParam) ; 
1425   }
1426   
1427   if (fRunGlobalQA) {
1428     Bool_t sameCycle = kFALSE ;
1429     if (!fQASteer) fQASteer = new AliQADataMakerSteer("rec") ; 
1430     AliQADataMaker *qadm = fQASteer->GetQADataMaker(AliQA::kGLOBAL);
1431     AliInfo(Form("Initializing the global QA data maker"));
1432     if (fQATasks.Contains(Form("%d", AliQA::kRECPOINTS))) {
1433       qadm->StartOfCycle(AliQA::kRECPOINTS, AliCDBManager::Instance()->GetRun(), sameCycle) ; 
1434       TObjArray *arr=qadm->Init(AliQA::kRECPOINTS);
1435       AliTracker::SetResidualsArray(arr);
1436       sameCycle = kTRUE ; 
1437     }
1438     if (fQATasks.Contains(Form("%d", AliQA::kESDS))) {
1439       qadm->StartOfCycle(AliQA::kESDS, AliCDBManager::Instance()->GetRun(), sameCycle) ; 
1440       qadm->Init(AliQA::kESDS);
1441     }
1442   }
1443
1444   //Initialize the Plane Efficiency framework
1445   if (fRunPlaneEff && !InitPlaneEff()) {
1446     Abort("InitPlaneEff", TSelector::kAbortProcess);
1447     return;
1448   }
1449
1450   if (strcmp(gProgName,"alieve") == 0)
1451     fRunAliEVE = InitAliEVE();
1452
1453   return;
1454 }
1455
1456 //_____________________________________________________________________________
1457 Bool_t AliReconstruction::Process(Long64_t entry)
1458 {
1459   // run the reconstruction over a single entry
1460   // from the chain with raw data
1461   AliCodeTimerAuto("");
1462
1463   TTree *currTree = fChain->GetTree();
1464   AliRawEvent *event = new AliRawEvent;
1465   currTree->SetBranchAddress("rawevent",&event);
1466   currTree->GetEntry(entry);
1467   fRawReader = new AliRawReaderRoot(event);
1468   fStatus = ProcessEvent(fRunLoader->GetNumberOfEvents());  
1469   delete fRawReader;
1470   fRawReader = NULL;
1471   delete event;
1472
1473   return fStatus;
1474 }
1475
1476 //_____________________________________________________________________________
1477 void AliReconstruction::Init(TTree *tree)
1478 {
1479   if (tree == 0) {
1480     AliError("The input tree is not found!");
1481     return;
1482   }
1483   fChain = tree;
1484 }
1485
1486 //_____________________________________________________________________________
1487 Bool_t AliReconstruction::ProcessEvent(Int_t iEvent)
1488 {
1489   // run the reconstruction over a single event
1490   // The event loop is steered in Run method
1491
1492   AliCodeTimerAuto("");
1493
1494   if (iEvent >= fRunLoader->GetNumberOfEvents()) {
1495     fRunLoader->SetEventNumber(iEvent);
1496     fRunLoader->GetHeader()->Reset(fRawReader->GetRunNumber(), 
1497                                    iEvent, iEvent);
1498     fRunLoader->TreeE()->Fill();
1499     if (fRawReader && fRawReader->UseAutoSaveESD())
1500       fRunLoader->TreeE()->AutoSave("SaveSelf");
1501   }
1502
1503   if ((iEvent < fFirstEvent) || ((fLastEvent >= 0) && (iEvent > fLastEvent))) {
1504     return kTRUE;
1505   }
1506
1507   AliInfo(Form("processing event %d", iEvent));
1508
1509   // Fill Event-info object
1510   GetEventInfo();
1511   fRecoParam.SetEventSpecie(fRunInfo,fEventInfo);
1512   AliInfo(Form("Current event specie: %s",fRecoParam.PrintEventSpecie()));
1513
1514   // Set the reco-params
1515   {
1516     TString detStr = fLoadCDB;
1517     for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
1518       if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
1519       AliReconstructor *reconstructor = GetReconstructor(iDet);
1520       if (reconstructor && fRecoParam.GetDetRecoParamArray(iDet)) {
1521         const AliDetectorRecoParam *par = fRecoParam.GetDetRecoParam(iDet);
1522         reconstructor->SetRecoParam(par);
1523       }
1524     }
1525   }
1526
1527   fRunLoader->GetEvent(iEvent);
1528
1529     // QA on single raw 
1530     if (fRunQA) 
1531                         fQASteer->RunOneEvent(fRawReader) ;  
1532
1533     // local single event reconstruction
1534     if (!fRunLocalReconstruction.IsNull()) {
1535       TString detectors=fRunLocalReconstruction;
1536       // run HLT event reconstruction first
1537       // ;-( IsSelected changes the string
1538       if (IsSelected("HLT", detectors) &&
1539           !RunLocalEventReconstruction("HLT")) {
1540         if (fStopOnError) {CleanUp(); return kFALSE;}
1541       }
1542       detectors=fRunLocalReconstruction;
1543       detectors.ReplaceAll("HLT", "");
1544       if (!RunLocalEventReconstruction(detectors)) {
1545         if (fStopOnError) {CleanUp(); return kFALSE;}
1546       }
1547     }
1548
1549     fesd->SetRunNumber(fRunLoader->GetHeader()->GetRun());
1550     fhltesd->SetRunNumber(fRunLoader->GetHeader()->GetRun());
1551     fesd->SetEventNumberInFile(fRunLoader->GetHeader()->GetEventNrInRun());
1552     fhltesd->SetEventNumberInFile(fRunLoader->GetHeader()->GetEventNrInRun());
1553     
1554     // Set magnetic field from the tracker
1555     fesd->SetMagneticField(AliTracker::GetBz());
1556     fhltesd->SetMagneticField(AliTracker::GetBz());
1557
1558     // Set most probable pt, for B=0 tracking
1559     // Get the global reco-params. They are atposition 16 inside the array of detectors in fRecoParam
1560     const AliGRPRecoParam *grpRecoParam = dynamic_cast<const AliGRPRecoParam*>(fRecoParam.GetDetRecoParam(kNDetectors));
1561     if (grpRecoParam) AliExternalTrackParam::SetMostProbablePt(grpRecoParam->GetMostProbablePt());
1562     
1563     // Fill raw-data error log into the ESD
1564     if (fRawReader) FillRawDataErrorLog(iEvent,fesd);
1565
1566     // vertex finder
1567     if (fRunVertexFinder) {
1568       if (!RunVertexFinder(fesd)) {
1569         if (fStopOnError) {CleanUp(); return kFALSE;}
1570       }
1571     }
1572
1573     // Muon tracking
1574     if (!fRunTracking.IsNull()) {
1575       if (fRunMuonTracking) {
1576         if (!RunMuonTracking(fesd)) {
1577           if (fStopOnError) {CleanUp(); return kFALSE;}
1578         }
1579       }
1580     }
1581
1582     // barrel tracking
1583     if (!fRunTracking.IsNull()) {
1584       if (!RunTracking(fesd)) {
1585         if (fStopOnError) {CleanUp(); return kFALSE;}
1586       }
1587     }
1588
1589     // fill ESD
1590     if (!fFillESD.IsNull()) {
1591       TString detectors=fFillESD;
1592       // run HLT first and on hltesd
1593       // ;-( IsSelected changes the string
1594       if (IsSelected("HLT", detectors) &&
1595           !FillESD(fhltesd, "HLT")) {
1596         if (fStopOnError) {CleanUp(); return kFALSE;}
1597       }
1598       detectors=fFillESD;
1599       // Temporary fix to avoid problems with HLT that overwrites the offline ESDs
1600       if (detectors.Contains("ALL")) {
1601         detectors="";
1602         for (Int_t idet=0; idet<kNDetectors; ++idet){
1603           detectors += fgkDetectorName[idet];
1604           detectors += " ";
1605         }
1606       }
1607       detectors.ReplaceAll("HLT", "");
1608       if (!FillESD(fesd, detectors)) {
1609         if (fStopOnError) {CleanUp(); return kFALSE;}
1610       }
1611     }
1612   
1613     // fill Event header information from the RawEventHeader
1614     if (fRawReader){FillRawEventHeaderESD(fesd);}
1615
1616     // combined PID
1617     AliESDpid::MakePID(fesd);
1618
1619     if (fFillTriggerESD) {
1620       if (!FillTriggerESD(fesd)) {
1621         if (fStopOnError) {CleanUp(); return kFALSE;}
1622       }
1623     }
1624
1625     ffile->cd();
1626
1627     //
1628     // Propagate track to the beam pipe  (if not already done by ITS)
1629     //
1630     const Int_t ntracks = fesd->GetNumberOfTracks();
1631     const Double_t kBz = fesd->GetMagneticField();
1632     const Double_t kRadius  = 2.8; //something less than the beam pipe radius
1633
1634     TObjArray trkArray;
1635     UShort_t *selectedIdx=new UShort_t[ntracks];
1636
1637     for (Int_t itrack=0; itrack<ntracks; itrack++){
1638       const Double_t kMaxStep = 5;   //max step over the material
1639       Bool_t ok;
1640
1641       AliESDtrack *track = fesd->GetTrack(itrack);
1642       if (!track) continue;
1643
1644       AliExternalTrackParam *tpcTrack =
1645            (AliExternalTrackParam *)track->GetTPCInnerParam();
1646       ok = kFALSE;
1647       if (tpcTrack)
1648         ok = AliTracker::
1649           PropagateTrackTo(tpcTrack,kRadius,track->GetMass(),kMaxStep,kFALSE);
1650
1651       if (ok) {
1652         Int_t n=trkArray.GetEntriesFast();
1653         selectedIdx[n]=track->GetID();
1654         trkArray.AddLast(tpcTrack);
1655       }
1656
1657       //Tracks refitted by ITS should already be at the SPD vertex
1658       if (track->IsOn(AliESDtrack::kITSrefit)) continue;
1659
1660       AliTracker::
1661          PropagateTrackTo(track,kRadius,track->GetMass(),kMaxStep,kFALSE);
1662       track->RelateToVertex(fesd->GetPrimaryVertexSPD(), kBz, kVeryBig);
1663
1664     }
1665
1666     //
1667     // Improve the reconstructed primary vertex position using the tracks
1668     //
1669     Bool_t runVertexFinderTracks = fRunVertexFinderTracks;
1670     if(fesd->GetPrimaryVertexSPD()) {
1671       TString vtitle = fesd->GetPrimaryVertexSPD()->GetTitle();
1672       if(vtitle.Contains("cosmics")) {
1673         runVertexFinderTracks=kFALSE;
1674       }
1675     }
1676
1677     if (runVertexFinderTracks) {
1678        // TPC + ITS primary vertex
1679        ftVertexer->SetITSMode();
1680        ftVertexer->SetConstraintOff();
1681        // get cuts for vertexer from AliGRPRecoParam
1682        if (grpRecoParam) {
1683          Int_t nCutsVertexer = grpRecoParam->GetVertexerTracksNCuts();
1684          Double_t *cutsVertexer = new Double_t[nCutsVertexer];
1685          grpRecoParam->GetVertexerTracksCutsITS(cutsVertexer);
1686          ftVertexer->SetCuts(cutsVertexer);
1687          delete [] cutsVertexer; cutsVertexer = NULL; 
1688          if(fDiamondProfile && grpRecoParam->GetVertexerTracksConstraintITS())
1689            ftVertexer->SetVtxStart(fDiamondProfile);
1690        }
1691        AliESDVertex *pvtx=ftVertexer->FindPrimaryVertex(fesd);
1692        if (pvtx) {
1693           if (pvtx->GetStatus()) {
1694              fesd->SetPrimaryVertexTracks(pvtx);
1695              for (Int_t i=0; i<ntracks; i++) {
1696                  AliESDtrack *t = fesd->GetTrack(i);
1697                  t->RelateToVertex(pvtx, kBz, kVeryBig);
1698              } 
1699           }
1700        }
1701
1702        // TPC-only primary vertex
1703        ftVertexer->SetTPCMode();
1704        ftVertexer->SetConstraintOff();
1705        // get cuts for vertexer from AliGRPRecoParam
1706        if (grpRecoParam) {
1707          Int_t nCutsVertexer = grpRecoParam->GetVertexerTracksNCuts();
1708          Double_t *cutsVertexer = new Double_t[nCutsVertexer];
1709          grpRecoParam->GetVertexerTracksCutsTPC(cutsVertexer);
1710          ftVertexer->SetCuts(cutsVertexer);
1711          delete [] cutsVertexer; cutsVertexer = NULL; 
1712          if(fDiamondProfileTPC && grpRecoParam->GetVertexerTracksConstraintTPC())
1713            ftVertexer->SetVtxStart(fDiamondProfileTPC);
1714        }
1715        pvtx=ftVertexer->FindPrimaryVertex(&trkArray,selectedIdx);
1716        if (pvtx) {
1717           if (pvtx->GetStatus()) {
1718              fesd->SetPrimaryVertexTPC(pvtx);
1719              for (Int_t i=0; i<ntracks; i++) {
1720                  AliESDtrack *t = fesd->GetTrack(i);
1721                  t->RelateToVertexTPC(pvtx, kBz, kVeryBig);
1722              } 
1723           }
1724        }
1725
1726     }
1727     delete[] selectedIdx;
1728
1729     if(fDiamondProfile) fesd->SetDiamond(fDiamondProfile);
1730     
1731
1732     if (fRunV0Finder) {
1733        // V0 finding
1734        AliV0vertexer vtxer;
1735        vtxer.Tracks2V0vertices(fesd);
1736
1737        if (fRunCascadeFinder) {
1738           // Cascade finding
1739           AliCascadeVertexer cvtxer;
1740           cvtxer.V0sTracks2CascadeVertices(fesd);
1741        }
1742     }
1743  
1744     // write ESD
1745     if (fCleanESD) CleanESD(fesd);
1746
1747   if (fRunQA) 
1748     fQASteer->RunOneEvent(fesd) ; 
1749
1750   if (fRunGlobalQA) {
1751       AliQADataMaker *qadm = fQASteer->GetQADataMaker(AliQA::kGLOBAL);
1752       if (qadm && fQATasks.Contains(Form("%d", AliQA::kESDS)))
1753         qadm->Exec(AliQA::kESDS, fesd);
1754     }
1755
1756     if (fWriteESDfriend) {
1757       //      fesdf->~AliESDfriend();
1758       //  new (fesdf) AliESDfriend(); // Reset...
1759       fesd->GetESDfriend(fesdf);
1760     }
1761     ftree->Fill();
1762
1763     // Auto-save the ESD tree in case of prompt reco @P2
1764     if (fRawReader && fRawReader->UseAutoSaveESD()) {
1765       ftree->AutoSave("SaveSelf");
1766       TFile *friendfile = (TFile *)(gROOT->GetListOfFiles()->FindObject("AliESDfriends.root"));
1767       if (friendfile) friendfile->Save();
1768     }
1769
1770     // write HLT ESD
1771     fhlttree->Fill();
1772
1773     // call AliEVE
1774     if (fRunAliEVE) RunAliEVE();
1775
1776     fesd->Reset();
1777     fhltesd->Reset();
1778     if (fWriteESDfriend) {
1779       fesdf->~AliESDfriend();
1780       new (fesdf) AliESDfriend(); // Reset...
1781     }
1782  
1783     ProcInfo_t procInfo;
1784     gSystem->GetProcInfo(&procInfo);
1785     AliInfo(Form("Event %d -> Current memory usage %d %d",iEvent, procInfo.fMemResident, procInfo.fMemVirtual));
1786   
1787     fEventInfo.Reset();
1788     for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
1789       if (fReconstructor[iDet])
1790         fReconstructor[iDet]->SetRecoParam(NULL);
1791     }
1792         
1793   if (fRunQA || fRunGlobalQA) 
1794       fQASteer->Increment() ; 
1795   
1796     return kTRUE;
1797 }
1798
1799 //_____________________________________________________________________________
1800 void AliReconstruction::SlaveTerminate()
1801 {
1802   // Finalize the run on the slave side
1803   // Called after the exit
1804   // from the event loop
1805   AliCodeTimerAuto("");
1806
1807   if (fIsNewRunLoader) { // galice.root didn't exist
1808     fRunLoader->WriteHeader("OVERWRITE");
1809     fRunLoader->CdGAFile();
1810     fRunLoader->Write(0, TObject::kOverwrite);
1811   }
1812
1813   const TMap *cdbMap = AliCDBManager::Instance()->GetStorageMap();       
1814   const TList *cdbList = AliCDBManager::Instance()->GetRetrievedIds();   
1815                  
1816    TMap *cdbMapCopy = new TMap(cdbMap->GetEntries());    
1817    cdbMapCopy->SetOwner(1);      
1818    cdbMapCopy->SetName("cdbMap");        
1819    TIter iter(cdbMap->GetTable());       
1820          
1821    TPair* pair = 0;      
1822    while((pair = dynamic_cast<TPair*> (iter.Next()))){   
1823          TObjString* keyStr = dynamic_cast<TObjString*> (pair->Key());   
1824          TObjString* valStr = dynamic_cast<TObjString*> (pair->Value());         
1825          cdbMapCopy->Add(new TObjString(keyStr->GetName()), new TObjString(valStr->GetName()));  
1826    }     
1827          
1828    TList *cdbListCopy = new TList();     
1829    cdbListCopy->SetOwner(1);     
1830    cdbListCopy->SetName("cdbList");      
1831          
1832    TIter iter2(cdbList);         
1833          
1834         AliCDBId* id=0;
1835         while((id = dynamic_cast<AliCDBId*> (iter2.Next()))){    
1836          cdbListCopy->Add(new TObjString(id->ToString().Data()));        
1837    }     
1838          
1839    ftree->GetUserInfo()->Add(cdbMapCopy);        
1840    ftree->GetUserInfo()->Add(cdbListCopy);
1841
1842
1843   ffile->cd();
1844
1845   if (fWriteESDfriend)
1846     ftree->SetBranchStatus("ESDfriend*",0);
1847   // we want to have only one tree version number
1848   ftree->Write(ftree->GetName(),TObject::kOverwrite);
1849   fhlttree->Write();
1850
1851 // Finish with Plane Efficiency evaluation: before of CleanUp !!!
1852   if (fRunPlaneEff && !FinishPlaneEff()) {
1853    AliWarning("Finish PlaneEff evaluation failed");
1854   }
1855
1856   // End of cycle for the in-loop  
1857   if (fRunQA) {
1858     fQASteer->EndOfCycle() ;
1859   }
1860   if (fRunGlobalQA) {
1861     AliQADataMaker *qadm = fQASteer->GetQADataMaker(AliQA::kGLOBAL);
1862     if (qadm) {
1863       if (fQATasks.Contains(Form("%d", AliQA::kRECPOINTS))) 
1864         qadm->EndOfCycle(AliQA::kRECPOINTS);
1865       if (fQATasks.Contains(Form("%d", AliQA::kESDS))) 
1866         qadm->EndOfCycle(AliQA::kESDS);
1867       qadm->Finish();
1868     }
1869   }
1870   gROOT->cd();
1871   CleanUp();
1872 }
1873     
1874 //_____________________________________________________________________________
1875 void AliReconstruction::Terminate()
1876 {
1877   // Create tags for the events in the ESD tree (the ESD tree is always present)
1878   // In case of empty events the tags will contain dummy values
1879   AliCodeTimerAuto("");
1880
1881   AliESDTagCreator *esdtagCreator = new AliESDTagCreator();
1882   esdtagCreator->CreateESDTags(fFirstEvent,fLastEvent,fGRPData);
1883
1884   // Cleanup of CDB manager: cache and active storages!
1885   AliCDBManager::Instance()->ClearCache();
1886 }
1887
1888 //_____________________________________________________________________________
1889 Bool_t AliReconstruction::RunLocalEventReconstruction(const TString& detectors)
1890 {
1891 // run the local reconstruction
1892
1893   static Int_t eventNr=0;
1894   AliCodeTimerAuto("")
1895
1896   TString detStr = detectors;
1897   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
1898     if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
1899     AliReconstructor* reconstructor = GetReconstructor(iDet);
1900     if (!reconstructor) continue;
1901     AliLoader* loader = fLoader[iDet];
1902     // Matthias April 2008: temporary fix to run HLT reconstruction
1903     // although the HLT loader is missing
1904     if (strcmp(fgkDetectorName[iDet], "HLT")==0) {
1905       if (fRawReader) {
1906         reconstructor->Reconstruct(fRawReader, NULL);
1907       } else {
1908         TTree* dummy=NULL;
1909         reconstructor->Reconstruct(dummy, NULL);
1910       }
1911       continue;
1912     }
1913     if (!loader) {
1914       AliWarning(Form("No loader is defined for %s!",fgkDetectorName[iDet]));
1915       continue;
1916     }
1917     // conversion of digits
1918     if (fRawReader && reconstructor->HasDigitConversion()) {
1919       AliInfo(Form("converting raw data digits into root objects for %s", 
1920                    fgkDetectorName[iDet]));
1921 //      AliCodeTimerAuto(Form("converting raw data digits into root objects for %s", 
1922 //                            fgkDetectorName[iDet]));
1923       loader->LoadDigits("update");
1924       loader->CleanDigits();
1925       loader->MakeDigitsContainer();
1926       TTree* digitsTree = loader->TreeD();
1927       reconstructor->ConvertDigits(fRawReader, digitsTree);
1928       loader->WriteDigits("OVERWRITE");
1929       loader->UnloadDigits();
1930     }
1931     // local reconstruction
1932     AliInfo(Form("running reconstruction for %s", fgkDetectorName[iDet]));
1933     //AliCodeTimerAuto(Form("running reconstruction for %s", fgkDetectorName[iDet]));
1934     loader->LoadRecPoints("update");
1935     loader->CleanRecPoints();
1936     loader->MakeRecPointsContainer();
1937     TTree* clustersTree = loader->TreeR();
1938     if (fRawReader && !reconstructor->HasDigitConversion()) {
1939       reconstructor->Reconstruct(fRawReader, clustersTree);
1940     } else {
1941       loader->LoadDigits("read");
1942       TTree* digitsTree = loader->TreeD();
1943       if (!digitsTree) {
1944         AliError(Form("Can't get the %s digits tree", fgkDetectorName[iDet]));
1945         if (fStopOnError) return kFALSE;
1946       } else {
1947         reconstructor->Reconstruct(digitsTree, clustersTree);
1948       }
1949       loader->UnloadDigits();
1950     }
1951
1952                 TString detQAStr(fQADetectors) ; 
1953                 if (fRunQA) 
1954                         fQASteer->RunOneEventInOneDetector(iDet, clustersTree) ; 
1955     
1956         loader->WriteRecPoints("OVERWRITE");
1957         loader->UnloadRecPoints();
1958         AliSysInfo::AddStamp(Form("LRec%s_%d",fgkDetectorName[iDet],eventNr), iDet,1,eventNr);
1959   }
1960   if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
1961     AliError(Form("the following detectors were not found: %s",
1962                   detStr.Data()));
1963     if (fStopOnError) return kFALSE;
1964   }
1965   eventNr++;
1966   return kTRUE;
1967 }
1968
1969 //_____________________________________________________________________________
1970 Bool_t AliReconstruction::RunVertexFinder(AliESDEvent*& esd)
1971 {
1972 // run the barrel tracking
1973
1974   AliCodeTimerAuto("")
1975
1976   AliESDVertex* vertex = NULL;
1977   Double_t vtxPos[3] = {0, 0, 0};
1978   Double_t vtxErr[3] = {0.07, 0.07, 0.1};
1979   TArrayF mcVertex(3); 
1980   if (fRunLoader->GetHeader() && fRunLoader->GetHeader()->GenEventHeader()) {
1981     fRunLoader->GetHeader()->GenEventHeader()->PrimaryVertex(mcVertex);
1982     for (Int_t i = 0; i < 3; i++) vtxPos[i] = mcVertex[i];
1983   }
1984
1985   if (fVertexer) {
1986     AliInfo("running the ITS vertex finder");
1987     if (fLoader[0]) {
1988       fLoader[0]->LoadRecPoints();
1989       TTree* cltree = fLoader[0]->TreeR();
1990       if (cltree) {
1991         if(fDiamondProfileSPD) fVertexer->SetVtxStart(fDiamondProfileSPD);
1992         vertex = fVertexer->FindVertexForCurrentEvent(cltree);
1993       }
1994       else {
1995         AliError("Can't get the ITS cluster tree");
1996       }
1997       fLoader[0]->UnloadRecPoints();
1998     }
1999     else {
2000       AliError("Can't get the ITS loader");
2001     }
2002     if(!vertex){
2003       AliWarning("Vertex not found");
2004       vertex = new AliESDVertex();
2005       vertex->SetName("default");
2006     }
2007     else {
2008       vertex->SetName("reconstructed");
2009     }
2010
2011   } else {
2012     AliInfo("getting the primary vertex from MC");
2013     vertex = new AliESDVertex(vtxPos, vtxErr);
2014   }
2015
2016   if (vertex) {
2017     vertex->GetXYZ(vtxPos);
2018     vertex->GetSigmaXYZ(vtxErr);
2019   } else {
2020     AliWarning("no vertex reconstructed");
2021     vertex = new AliESDVertex(vtxPos, vtxErr);
2022   }
2023   esd->SetPrimaryVertexSPD(vertex);
2024   // if SPD multiplicity has been determined, it is stored in the ESD
2025   AliMultiplicity *mult = fVertexer->GetMultiplicity();
2026   if(mult)esd->SetMultiplicity(mult);
2027
2028   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
2029     if (fTracker[iDet]) fTracker[iDet]->SetVertex(vtxPos, vtxErr);
2030   }  
2031   delete vertex;
2032
2033   return kTRUE;
2034 }
2035
2036 //_____________________________________________________________________________
2037 Bool_t AliReconstruction::RunHLTTracking(AliESDEvent*& esd)
2038 {
2039 // run the HLT barrel tracking
2040
2041   AliCodeTimerAuto("")
2042
2043   if (!fRunLoader) {
2044     AliError("Missing runLoader!");
2045     return kFALSE;
2046   }
2047
2048   AliInfo("running HLT tracking");
2049
2050   // Get a pointer to the HLT reconstructor
2051   AliReconstructor *reconstructor = GetReconstructor(kNDetectors-1);
2052   if (!reconstructor) return kFALSE;
2053
2054   // TPC + ITS
2055   for (Int_t iDet = 1; iDet >= 0; iDet--) {
2056     TString detName = fgkDetectorName[iDet];
2057     AliDebug(1, Form("%s HLT tracking", detName.Data()));
2058     reconstructor->SetOption(detName.Data());
2059     AliTracker *tracker = reconstructor->CreateTracker();
2060     if (!tracker) {
2061       AliWarning(Form("couldn't create a HLT tracker for %s", detName.Data()));
2062       if (fStopOnError) return kFALSE;
2063       continue;
2064     }
2065     Double_t vtxPos[3];
2066     Double_t vtxErr[3]={0.005,0.005,0.010};
2067     const AliESDVertex *vertex = esd->GetVertex();
2068     vertex->GetXYZ(vtxPos);
2069     tracker->SetVertex(vtxPos,vtxErr);
2070     if(iDet != 1) {
2071       fLoader[iDet]->LoadRecPoints("read");
2072       TTree* tree = fLoader[iDet]->TreeR();
2073       if (!tree) {
2074         AliError(Form("Can't get the %s cluster tree", detName.Data()));
2075         return kFALSE;
2076       }
2077       tracker->LoadClusters(tree);
2078     }
2079     if (tracker->Clusters2Tracks(esd) != 0) {
2080       AliError(Form("HLT %s Clusters2Tracks failed", fgkDetectorName[iDet]));
2081       return kFALSE;
2082     }
2083     if(iDet != 1) {
2084       tracker->UnloadClusters();
2085     }
2086     delete tracker;
2087   }
2088
2089   return kTRUE;
2090 }
2091
2092 //_____________________________________________________________________________
2093 Bool_t AliReconstruction::RunMuonTracking(AliESDEvent*& esd)
2094 {
2095 // run the muon spectrometer tracking
2096
2097   AliCodeTimerAuto("")
2098
2099   if (!fRunLoader) {
2100     AliError("Missing runLoader!");
2101     return kFALSE;
2102   }
2103   Int_t iDet = 7; // for MUON
2104
2105   AliInfo("is running...");
2106
2107   // Get a pointer to the MUON reconstructor
2108   AliReconstructor *reconstructor = GetReconstructor(iDet);
2109   if (!reconstructor) return kFALSE;
2110
2111   
2112   TString detName = fgkDetectorName[iDet];
2113   AliDebug(1, Form("%s tracking", detName.Data()));
2114   AliTracker *tracker =  reconstructor->CreateTracker();
2115   if (!tracker) {
2116     AliWarning(Form("couldn't create a tracker for %s", detName.Data()));
2117     return kFALSE;
2118   }
2119      
2120   // read RecPoints
2121   fLoader[iDet]->LoadRecPoints("read");  
2122
2123   tracker->LoadClusters(fLoader[iDet]->TreeR());
2124   
2125   Int_t rv = tracker->Clusters2Tracks(esd);
2126   
2127   if ( rv )
2128   {
2129     AliError(Form("%s Clusters2Tracks failed", fgkDetectorName[iDet]));
2130     return kFALSE;
2131   }
2132   
2133   fLoader[iDet]->UnloadRecPoints();
2134
2135   tracker->UnloadClusters();
2136   
2137   delete tracker;
2138   
2139   return kTRUE;
2140 }
2141
2142
2143 //_____________________________________________________________________________
2144 Bool_t AliReconstruction::RunTracking(AliESDEvent*& esd)
2145 {
2146 // run the barrel tracking
2147   static Int_t eventNr=0;
2148   AliCodeTimerAuto("")
2149
2150   AliInfo("running tracking");
2151
2152   //Fill the ESD with the T0 info (will be used by the TOF) 
2153   if (fReconstructor[11] && fLoader[11]) {
2154     fLoader[11]->LoadRecPoints("READ");
2155     TTree *treeR = fLoader[11]->TreeR();
2156     if (treeR) {
2157       GetReconstructor(11)->FillESD((TTree *)NULL,treeR,esd);
2158     }
2159   }
2160
2161   // pass 1: TPC + ITS inwards
2162   for (Int_t iDet = 1; iDet >= 0; iDet--) {
2163     if (!fTracker[iDet]) continue;
2164     AliDebug(1, Form("%s tracking", fgkDetectorName[iDet]));
2165
2166     // load clusters
2167     fLoader[iDet]->LoadRecPoints("read");
2168     AliSysInfo::AddStamp(Form("RLoadCluster%s_%d",fgkDetectorName[iDet],eventNr),iDet,1, eventNr);
2169     TTree* tree = fLoader[iDet]->TreeR();
2170     if (!tree) {
2171       AliError(Form("Can't get the %s cluster tree", fgkDetectorName[iDet]));
2172       return kFALSE;
2173     }
2174     fTracker[iDet]->LoadClusters(tree);
2175     AliSysInfo::AddStamp(Form("TLoadCluster%s_%d",fgkDetectorName[iDet],eventNr), iDet,2, eventNr);
2176     // run tracking
2177     if (fTracker[iDet]->Clusters2Tracks(esd) != 0) {
2178       AliError(Form("%s Clusters2Tracks failed", fgkDetectorName[iDet]));
2179       return kFALSE;
2180     }
2181     // preliminary PID in TPC needed by the ITS tracker
2182     if (iDet == 1) {
2183       GetReconstructor(1)->FillESD((TTree*)NULL, (TTree*)NULL, esd);
2184       AliESDpid::MakePID(esd);
2185     } 
2186     AliSysInfo::AddStamp(Form("Tracking0%s_%d",fgkDetectorName[iDet],eventNr), iDet,3,eventNr);
2187   }
2188
2189   // pass 2: ALL backwards
2190
2191   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
2192     if (!fTracker[iDet]) continue;
2193     AliDebug(1, Form("%s back propagation", fgkDetectorName[iDet]));
2194
2195     // load clusters
2196     if (iDet > 1) {     // all except ITS, TPC
2197       TTree* tree = NULL;
2198       fLoader[iDet]->LoadRecPoints("read");
2199       AliSysInfo::AddStamp(Form("RLoadCluster0%s_%d",fgkDetectorName[iDet],eventNr), iDet,1, eventNr);
2200       tree = fLoader[iDet]->TreeR();
2201       if (!tree) {
2202         AliError(Form("Can't get the %s cluster tree", fgkDetectorName[iDet]));
2203         return kFALSE;
2204       }
2205       fTracker[iDet]->LoadClusters(tree); 
2206       AliSysInfo::AddStamp(Form("TLoadCluster0%s_%d",fgkDetectorName[iDet],eventNr), iDet,2, eventNr);
2207     }
2208
2209     // run tracking
2210     if (iDet>1) // start filling residuals for the "outer" detectors
2211     if (fRunGlobalQA) AliTracker::SetFillResiduals(kTRUE);     
2212
2213     if (fTracker[iDet]->PropagateBack(esd) != 0) {
2214       AliError(Form("%s backward propagation failed", fgkDetectorName[iDet]));
2215       //      return kFALSE;
2216     }
2217
2218     // unload clusters
2219     if (iDet > 3) {     // all except ITS, TPC, TRD and TOF
2220       fTracker[iDet]->UnloadClusters();
2221       fLoader[iDet]->UnloadRecPoints();
2222     }
2223     // updated PID in TPC needed by the ITS tracker -MI
2224     if (iDet == 1) {
2225       GetReconstructor(1)->FillESD((TTree*)NULL, (TTree*)NULL, esd);
2226       AliESDpid::MakePID(esd);
2227     }
2228     AliSysInfo::AddStamp(Form("Tracking1%s_%d",fgkDetectorName[iDet],eventNr), iDet,3, eventNr);
2229   }
2230   //stop filling residuals for the "outer" detectors
2231   if (fRunGlobalQA) AliTracker::SetFillResiduals(kFALSE);     
2232
2233   // pass 3: TRD + TPC + ITS refit inwards
2234
2235   for (Int_t iDet = 2; iDet >= 0; iDet--) {
2236     if (!fTracker[iDet]) continue;
2237     AliDebug(1, Form("%s inward refit", fgkDetectorName[iDet]));
2238
2239     // run tracking
2240     if (iDet<2) // start filling residuals for TPC and ITS
2241     if (fRunGlobalQA) AliTracker::SetFillResiduals(kTRUE);     
2242
2243     if (fTracker[iDet]->RefitInward(esd) != 0) {
2244       AliError(Form("%s inward refit failed", fgkDetectorName[iDet]));
2245       //      return kFALSE;
2246     }
2247     // run postprocessing
2248     if (fTracker[iDet]->PostProcess(esd) != 0) {
2249       AliError(Form("%s postprocessing failed", fgkDetectorName[iDet]));
2250       //      return kFALSE;
2251     }
2252     AliSysInfo::AddStamp(Form("Tracking2%s_%d",fgkDetectorName[iDet],eventNr), iDet,3, eventNr);
2253   }
2254
2255   // write space-points to the ESD in case alignment data output
2256   // is switched on
2257   if (fWriteAlignmentData)
2258     WriteAlignmentData(esd);
2259
2260   for (Int_t iDet = 3; iDet >= 0; iDet--) {
2261     if (!fTracker[iDet]) continue;
2262     // unload clusters
2263     fTracker[iDet]->UnloadClusters();
2264     AliSysInfo::AddStamp(Form("TUnloadCluster%s_%d",fgkDetectorName[iDet],eventNr), iDet,4, eventNr);
2265     fLoader[iDet]->UnloadRecPoints();
2266     AliSysInfo::AddStamp(Form("RUnloadCluster%s_%d",fgkDetectorName[iDet],eventNr), iDet,5, eventNr);
2267   }
2268   // stop filling residuals for TPC and ITS
2269   if (fRunGlobalQA) AliTracker::SetFillResiduals(kFALSE);     
2270
2271   eventNr++;
2272   return kTRUE;
2273 }
2274
2275 //_____________________________________________________________________________
2276 Bool_t AliReconstruction::CleanESD(AliESDEvent *esd){
2277   //
2278   // Remove the data which are not needed for the physics analysis.
2279   //
2280
2281   Int_t nTracks=esd->GetNumberOfTracks();
2282   Int_t nV0s=esd->GetNumberOfV0s();
2283   AliInfo
2284   (Form("Number of ESD tracks and V0s before cleaning: %d %d",nTracks,nV0s));
2285
2286   Float_t cleanPars[]={fV0DCAmax,fV0CsPmin,fDmax,fZmax};
2287   Bool_t rc=esd->Clean(cleanPars);
2288
2289   nTracks=esd->GetNumberOfTracks();
2290   nV0s=esd->GetNumberOfV0s();
2291   AliInfo
2292   (Form("Number of ESD tracks and V0s after cleaning %d %d",nTracks,nV0s));
2293
2294   return rc;
2295 }
2296
2297 //_____________________________________________________________________________
2298 Bool_t AliReconstruction::FillESD(AliESDEvent*& esd, const TString& detectors)
2299 {
2300 // fill the event summary data
2301
2302   AliCodeTimerAuto("")
2303     static Int_t eventNr=0; 
2304   TString detStr = detectors;
2305   
2306   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
2307   if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
2308     AliReconstructor* reconstructor = GetReconstructor(iDet);
2309     if (!reconstructor) continue;
2310     AliDebug(1, Form("filling ESD for %s", fgkDetectorName[iDet]));
2311     TTree* clustersTree = NULL;
2312     if (fLoader[iDet]) {
2313       fLoader[iDet]->LoadRecPoints("read");
2314       clustersTree = fLoader[iDet]->TreeR();
2315       if (!clustersTree) {
2316         AliError(Form("Can't get the %s clusters tree", 
2317                       fgkDetectorName[iDet]));
2318         if (fStopOnError) return kFALSE;
2319       }
2320     }
2321     if (fRawReader && !reconstructor->HasDigitConversion()) {
2322       reconstructor->FillESD(fRawReader, clustersTree, esd);
2323     } else {
2324       TTree* digitsTree = NULL;
2325       if (fLoader[iDet]) {
2326         fLoader[iDet]->LoadDigits("read");
2327         digitsTree = fLoader[iDet]->TreeD();
2328         if (!digitsTree) {
2329           AliError(Form("Can't get the %s digits tree", 
2330                         fgkDetectorName[iDet]));
2331           if (fStopOnError) return kFALSE;
2332         }
2333       }
2334       reconstructor->FillESD(digitsTree, clustersTree, esd);
2335       if (fLoader[iDet]) fLoader[iDet]->UnloadDigits();
2336     }
2337     if (fLoader[iDet]) {
2338       fLoader[iDet]->UnloadRecPoints();
2339     }
2340   }
2341
2342   if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
2343     AliError(Form("the following detectors were not found: %s", 
2344                   detStr.Data()));
2345     if (fStopOnError) return kFALSE;
2346   }
2347   AliSysInfo::AddStamp(Form("FillESD%d",eventNr), 0,1, eventNr);
2348   eventNr++;
2349   return kTRUE;
2350 }
2351
2352 //_____________________________________________________________________________
2353 Bool_t AliReconstruction::FillTriggerESD(AliESDEvent*& esd)
2354 {
2355   // Reads the trigger decision which is
2356   // stored in Trigger.root file and fills
2357   // the corresponding esd entries
2358
2359   AliCodeTimerAuto("")
2360   
2361   AliInfo("Filling trigger information into the ESD");
2362
2363   if (fRawReader) {
2364     AliCTPRawStream input(fRawReader);
2365     if (!input.Next()) {
2366       AliWarning("No valid CTP (trigger) DDL raw data is found ! The trigger info is taken from the event header!");
2367     }
2368     else {
2369       if (esd->GetTriggerMask() != input.GetClassMask())
2370         AliError(Form("Invalid trigger pattern found in CTP raw-data: %llx %llx",
2371                       input.GetClassMask(),esd->GetTriggerMask()));
2372       if (esd->GetOrbitNumber() != input.GetOrbitID())
2373         AliError(Form("Invalid orbit id found in CTP raw-data: %x %x",
2374                       input.GetOrbitID(),esd->GetOrbitNumber()));
2375       if (esd->GetBunchCrossNumber() != input.GetBCID())
2376         AliError(Form("Invalid bunch-crossing id found in CTP raw-data: %x %x",
2377                       input.GetBCID(),esd->GetBunchCrossNumber()));
2378     }
2379
2380   // Here one has to add the filling of trigger inputs and
2381   // interaction records
2382   // ...
2383   }
2384   return kTRUE;
2385 }
2386
2387
2388
2389
2390
2391 //_____________________________________________________________________________
2392 Bool_t AliReconstruction::FillRawEventHeaderESD(AliESDEvent*& esd)
2393 {
2394   // 
2395   // Filling information from RawReader Header
2396   // 
2397
2398   if (!fRawReader) return kFALSE;
2399
2400   AliInfo("Filling information from RawReader Header");
2401
2402   esd->SetBunchCrossNumber(fRawReader->GetBCID());
2403   esd->SetOrbitNumber(fRawReader->GetOrbitID());
2404   esd->SetPeriodNumber(fRawReader->GetPeriod());
2405
2406   esd->SetTimeStamp(fRawReader->GetTimestamp());  
2407   esd->SetEventType(fRawReader->GetType());
2408
2409   return kTRUE;
2410 }
2411
2412
2413 //_____________________________________________________________________________
2414 Bool_t AliReconstruction::IsSelected(TString detName, TString& detectors) const
2415 {
2416 // check whether detName is contained in detectors
2417 // if yes, it is removed from detectors
2418
2419   // check if all detectors are selected
2420   if ((detectors.CompareTo("ALL") == 0) ||
2421       detectors.BeginsWith("ALL ") ||
2422       detectors.EndsWith(" ALL") ||
2423       detectors.Contains(" ALL ")) {
2424     detectors = "ALL";
2425     return kTRUE;
2426   }
2427
2428   // search for the given detector
2429   Bool_t result = kFALSE;
2430   if ((detectors.CompareTo(detName) == 0) ||
2431       detectors.BeginsWith(detName+" ") ||
2432       detectors.EndsWith(" "+detName) ||
2433       detectors.Contains(" "+detName+" ")) {
2434     detectors.ReplaceAll(detName, "");
2435     result = kTRUE;
2436   }
2437
2438   // clean up the detectors string
2439   while (detectors.Contains("  ")) detectors.ReplaceAll("  ", " ");
2440   while (detectors.BeginsWith(" ")) detectors.Remove(0, 1);
2441   while (detectors.EndsWith(" ")) detectors.Remove(detectors.Length()-1, 1);
2442
2443   return result;
2444 }
2445
2446 //_____________________________________________________________________________
2447 Bool_t AliReconstruction::InitRunLoader()
2448 {
2449 // get or create the run loader
2450
2451   if (gAlice) delete gAlice;
2452   gAlice = NULL;
2453
2454   if (!gSystem->AccessPathName(fGAliceFileName.Data())) { // galice.root exists
2455     // load all base libraries to get the loader classes
2456     TString libs = gSystem->GetLibraries();
2457     for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
2458       TString detName = fgkDetectorName[iDet];
2459       if (detName == "HLT") continue;
2460       if (libs.Contains("lib" + detName + "base.so")) continue;
2461       gSystem->Load("lib" + detName + "base.so");
2462     }
2463     fRunLoader = AliRunLoader::Open(fGAliceFileName.Data());
2464     if (!fRunLoader) {
2465       AliError(Form("no run loader found in file %s", fGAliceFileName.Data()));
2466       CleanUp();
2467       return kFALSE;
2468     }
2469
2470     fRunLoader->CdGAFile();
2471     fRunLoader->LoadgAlice();
2472
2473     //PH This is a temporary fix to give access to the kinematics
2474     //PH that is needed for the labels of ITS clusters
2475     fRunLoader->LoadHeader();
2476     fRunLoader->LoadKinematics();
2477
2478   } else {               // galice.root does not exist
2479     if (!fRawReader) {
2480       AliError(Form("the file %s does not exist", fGAliceFileName.Data()));
2481     }
2482     fRunLoader = AliRunLoader::Open(fGAliceFileName.Data(),
2483                                     AliConfig::GetDefaultEventFolderName(),
2484                                     "recreate");
2485     if (!fRunLoader) {
2486       AliError(Form("could not create run loader in file %s", 
2487                     fGAliceFileName.Data()));
2488       CleanUp();
2489       return kFALSE;
2490     }
2491     fIsNewRunLoader = kTRUE;
2492     fRunLoader->MakeTree("E");
2493
2494     if (fNumberOfEventsPerFile > 0)
2495       fRunLoader->SetNumberOfEventsPerFile(fNumberOfEventsPerFile);
2496     else
2497       fRunLoader->SetNumberOfEventsPerFile((UInt_t)-1);
2498   }
2499
2500   return kTRUE;
2501 }
2502
2503 //_____________________________________________________________________________
2504 AliReconstructor* AliReconstruction::GetReconstructor(Int_t iDet)
2505 {
2506 // get the reconstructor object and the loader for a detector
2507
2508   if (fReconstructor[iDet]) {
2509     if (fRecoParam.GetDetRecoParamArray(iDet) && !AliReconstructor::GetRecoParam(iDet)) {
2510       const AliDetectorRecoParam *par = fRecoParam.GetDetRecoParam(iDet);
2511       fReconstructor[iDet]->SetRecoParam(par);
2512     }
2513     return fReconstructor[iDet];
2514   }
2515
2516   // load the reconstructor object
2517   TPluginManager* pluginManager = gROOT->GetPluginManager();
2518   TString detName = fgkDetectorName[iDet];
2519   TString recName = "Ali" + detName + "Reconstructor";
2520
2521   if (!fIsNewRunLoader && !fRunLoader->GetLoader(detName+"Loader") && (detName != "HLT")) return NULL;
2522
2523   AliReconstructor* reconstructor = NULL;
2524   // first check if a plugin is defined for the reconstructor
2525   TPluginHandler* pluginHandler = 
2526     pluginManager->FindHandler("AliReconstructor", detName);
2527   // if not, add a plugin for it
2528   if (!pluginHandler) {
2529     AliDebug(1, Form("defining plugin for %s", recName.Data()));
2530     TString libs = gSystem->GetLibraries();
2531     if (libs.Contains("lib" + detName + "base.so") ||
2532         (gSystem->Load("lib" + detName + "base.so") >= 0)) {
2533       pluginManager->AddHandler("AliReconstructor", detName, 
2534                                 recName, detName + "rec", recName + "()");
2535     } else {
2536       pluginManager->AddHandler("AliReconstructor", detName, 
2537                                 recName, detName, recName + "()");
2538     }
2539     pluginHandler = pluginManager->FindHandler("AliReconstructor", detName);
2540   }
2541   if (pluginHandler && (pluginHandler->LoadPlugin() == 0)) {
2542     reconstructor = (AliReconstructor*) pluginHandler->ExecPlugin(0);
2543   }
2544   if (reconstructor) {
2545     TObject* obj = fOptions.FindObject(detName.Data());
2546     if (obj) reconstructor->SetOption(obj->GetTitle());
2547     reconstructor->Init();
2548     fReconstructor[iDet] = reconstructor;
2549   }
2550
2551   // get or create the loader
2552   if (detName != "HLT") {
2553     fLoader[iDet] = fRunLoader->GetLoader(detName + "Loader");
2554     if (!fLoader[iDet]) {
2555       AliConfig::Instance()
2556         ->CreateDetectorFolders(fRunLoader->GetEventFolder(), 
2557                                 detName, detName);
2558       // first check if a plugin is defined for the loader
2559       pluginHandler = 
2560         pluginManager->FindHandler("AliLoader", detName);
2561       // if not, add a plugin for it
2562       if (!pluginHandler) {
2563         TString loaderName = "Ali" + detName + "Loader";
2564         AliDebug(1, Form("defining plugin for %s", loaderName.Data()));
2565         pluginManager->AddHandler("AliLoader", detName, 
2566                                   loaderName, detName + "base", 
2567                                   loaderName + "(const char*, TFolder*)");
2568         pluginHandler = pluginManager->FindHandler("AliLoader", detName);
2569       }
2570       if (pluginHandler && (pluginHandler->LoadPlugin() == 0)) {
2571         fLoader[iDet] = 
2572           (AliLoader*) pluginHandler->ExecPlugin(2, detName.Data(), 
2573                                                  fRunLoader->GetEventFolder());
2574       }
2575       if (!fLoader[iDet]) {   // use default loader
2576         fLoader[iDet] = new AliLoader(detName, fRunLoader->GetEventFolder());
2577       }
2578       if (!fLoader[iDet]) {
2579         AliWarning(Form("couldn't get loader for %s", detName.Data()));
2580         if (fStopOnError) return NULL;
2581       } else {
2582         fRunLoader->AddLoader(fLoader[iDet]);
2583         fRunLoader->CdGAFile();
2584         if (gFile && !gFile->IsWritable()) gFile->ReOpen("UPDATE");
2585         fRunLoader->Write(0, TObject::kOverwrite);
2586       }
2587     }
2588   }
2589       
2590   if (fRecoParam.GetDetRecoParamArray(iDet) && !AliReconstructor::GetRecoParam(iDet)) {
2591     const AliDetectorRecoParam *par = fRecoParam.GetDetRecoParam(iDet);
2592     reconstructor->SetRecoParam(par);
2593   }
2594   return reconstructor;
2595 }
2596
2597 //_____________________________________________________________________________
2598 Bool_t AliReconstruction::CreateVertexer()
2599 {
2600 // create the vertexer
2601
2602   fVertexer = NULL;
2603   AliReconstructor* itsReconstructor = GetReconstructor(0);
2604   if (itsReconstructor) {
2605     fVertexer = itsReconstructor->CreateVertexer();
2606   }
2607   if (!fVertexer) {
2608     AliWarning("couldn't create a vertexer for ITS");
2609     if (fStopOnError) return kFALSE;
2610   }
2611
2612   return kTRUE;
2613 }
2614
2615 //_____________________________________________________________________________
2616 Bool_t AliReconstruction::CreateTrackers(const TString& detectors)
2617 {
2618 // create the trackers
2619         AliInfo("Creating trackers");
2620
2621   TString detStr = detectors;
2622   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
2623     if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
2624     AliReconstructor* reconstructor = GetReconstructor(iDet);
2625     if (!reconstructor) continue;
2626     TString detName = fgkDetectorName[iDet];
2627     if (detName == "HLT") {
2628       fRunHLTTracking = kTRUE;
2629       continue;
2630     }
2631     if (detName == "MUON") {
2632       fRunMuonTracking = kTRUE;
2633       continue;
2634     }
2635
2636
2637     fTracker[iDet] = reconstructor->CreateTracker();
2638     if (!fTracker[iDet] && (iDet < 7)) {
2639       AliWarning(Form("couldn't create a tracker for %s", detName.Data()));
2640       if (fStopOnError) return kFALSE;
2641     }
2642     AliSysInfo::AddStamp(Form("LTracker%s",fgkDetectorName[iDet]), iDet,0);
2643   }
2644
2645   return kTRUE;
2646 }
2647
2648 //_____________________________________________________________________________
2649 void AliReconstruction::CleanUp()
2650 {
2651 // delete trackers and the run loader and close and delete the file
2652
2653   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
2654     delete fReconstructor[iDet];
2655     fReconstructor[iDet] = NULL;
2656     fLoader[iDet] = NULL;
2657     delete fTracker[iDet];
2658     fTracker[iDet] = NULL;
2659   }
2660   delete fRunInfo;
2661   fRunInfo = NULL;
2662
2663   delete fVertexer;
2664   fVertexer = NULL;
2665
2666   delete ftVertexer;
2667   ftVertexer = NULL;
2668   
2669   if(!(AliCDBManager::Instance()->GetCacheFlag())) {
2670     delete fDiamondProfileSPD;
2671     fDiamondProfileSPD = NULL;
2672     delete fDiamondProfile;
2673     fDiamondProfile = NULL;
2674     delete fDiamondProfileTPC;
2675     fDiamondProfileTPC = NULL;
2676   }
2677   delete fRunLoader;
2678   fRunLoader = NULL;
2679   delete fRawReader;
2680   fRawReader = NULL;
2681   delete fParentRawReader;
2682   fParentRawReader=NULL;
2683
2684   if (ffile) {
2685     ffile->Close();
2686     delete ffile;
2687     ffile = NULL;
2688   }
2689 }
2690
2691 void AliReconstruction::WriteAlignmentData(AliESDEvent* esd)
2692 {
2693   // Write space-points which are then used in the alignment procedures
2694   // For the moment only ITS, TPC, TRD and TOF
2695
2696   Int_t ntracks = esd->GetNumberOfTracks();
2697   for (Int_t itrack = 0; itrack < ntracks; itrack++)
2698     {
2699       AliESDtrack *track = esd->GetTrack(itrack);
2700       Int_t nsp = 0;
2701       Int_t idx[200];
2702       for (Int_t iDet = 5; iDet >= 0; iDet--) {// TOF, TRD, TPC, ITS clusters
2703           nsp += track->GetNcls(iDet);
2704
2705           if (iDet==0) { // ITS "extra" clusters
2706              track->GetClusters(iDet,idx);
2707              for (Int_t i=6; i<12; i++) if(idx[i] >= 0) nsp++;
2708           }  
2709       }
2710
2711       if (nsp) {
2712         AliTrackPointArray *sp = new AliTrackPointArray(nsp);
2713         track->SetTrackPointArray(sp);
2714         Int_t isptrack = 0;
2715         for (Int_t iDet = 5; iDet >= 0; iDet--) {
2716           AliTracker *tracker = fTracker[iDet];
2717           if (!tracker) continue;
2718           Int_t nspdet = track->GetClusters(iDet,idx);
2719
2720           if (iDet==0) // ITS "extra" clusters             
2721              for (Int_t i=6; i<12; i++) if(idx[i] >= 0) nspdet++;
2722
2723           if (nspdet <= 0) continue;
2724           AliTrackPoint p;
2725           Int_t isp = 0;
2726           Int_t isp2 = 0;
2727           while (isp2 < nspdet) {
2728             Bool_t isvalid=kTRUE;
2729
2730             Int_t index=idx[isp++];
2731             if (index < 0) continue;
2732
2733             TString dets = fgkDetectorName[iDet];
2734             if ((fUseTrackingErrorsForAlignment.CompareTo(dets) == 0) ||
2735             fUseTrackingErrorsForAlignment.BeginsWith(dets+" ") ||
2736             fUseTrackingErrorsForAlignment.EndsWith(" "+dets) ||
2737             fUseTrackingErrorsForAlignment.Contains(" "+dets+" ")) {
2738               isvalid = tracker->GetTrackPointTrackingError(index,p,track);
2739             } else {
2740               isvalid = tracker->GetTrackPoint(index,p); 
2741             } 
2742             isp2++;
2743             if (!isvalid) continue;
2744             sp->AddPoint(isptrack,&p); isptrack++;
2745           }
2746         }       
2747       }
2748     }
2749 }
2750
2751 //_____________________________________________________________________________
2752 void AliReconstruction::FillRawDataErrorLog(Int_t iEvent, AliESDEvent* esd)
2753 {
2754   // The method reads the raw-data error log
2755   // accumulated within the rawReader.
2756   // It extracts the raw-data errors related to
2757   // the current event and stores them into
2758   // a TClonesArray inside the esd object.
2759
2760   if (!fRawReader) return;
2761
2762   for(Int_t i = 0; i < fRawReader->GetNumberOfErrorLogs(); i++) {
2763
2764     AliRawDataErrorLog *log = fRawReader->GetErrorLog(i);
2765     if (!log) continue;
2766     if (iEvent != log->GetEventNumber()) continue;
2767
2768     esd->AddRawDataErrorLog(log);
2769   }
2770
2771 }
2772
2773 //_____________________________________________________________________________
2774 void AliReconstruction::CheckQA()
2775 {
2776 // check the QA of SIM for this run and remove the detectors 
2777 // with status Fatal
2778   
2779         TString newRunLocalReconstruction ; 
2780         TString newRunTracking ;
2781         TString newFillESD ;
2782          
2783         for (Int_t iDet = 0; iDet < AliQA::kNDET; iDet++) {
2784                 TString detName(AliQA::GetDetName(iDet)) ;
2785                 AliQA * qa = AliQA::Instance(AliQA::DETECTORINDEX_t(iDet)) ; 
2786                 if ( qa->IsSet(AliQA::DETECTORINDEX_t(iDet), AliQA::kSIM, AliQA::kFATAL)) {
2787                                 AliInfo(Form("QA status for %s in Hits and/or SDIGITS  and/or Digits was Fatal; No reconstruction performed", detName.Data())) ;
2788                 } else {
2789                         if ( fRunLocalReconstruction.Contains(AliQA::GetDetName(iDet)) || 
2790                                         fRunLocalReconstruction.Contains("ALL") )  {
2791                                 newRunLocalReconstruction += detName ; 
2792                                 newRunLocalReconstruction += " " ;                      
2793                         }
2794                         if ( fRunTracking.Contains(AliQA::GetDetName(iDet)) || 
2795                                         fRunTracking.Contains("ALL") )  {
2796                                 newRunTracking += detName ; 
2797                                 newRunTracking += " " ;                         
2798                         }
2799                         if ( fFillESD.Contains(AliQA::GetDetName(iDet)) || 
2800                                         fFillESD.Contains("ALL") )  {
2801                                 newFillESD += detName ; 
2802                                 newFillESD += " " ;                     
2803                         }
2804                 }
2805         }
2806         fRunLocalReconstruction = newRunLocalReconstruction ; 
2807         fRunTracking            = newRunTracking ; 
2808         fFillESD                = newFillESD ; 
2809 }
2810
2811 //_____________________________________________________________________________
2812 Int_t AliReconstruction::GetDetIndex(const char* detector)
2813 {
2814   // return the detector index corresponding to detector
2815   Int_t index = -1 ; 
2816   for (index = 0; index < kNDetectors ; index++) {
2817     if ( strcmp(detector, fgkDetectorName[index]) == 0 )
2818         break ; 
2819   }     
2820   return index ; 
2821 }
2822 //_____________________________________________________________________________
2823 Bool_t AliReconstruction::FinishPlaneEff() {
2824  //
2825  // Here execute all the necessary operationis, at the end of the tracking phase,
2826  // in case that evaluation of PlaneEfficiencies was required for some detector.
2827  // E.g., write into a DataBase file the PlaneEfficiency which have been evaluated.
2828  //
2829  // This Preliminary version works only FOR ITS !!!!!
2830  // other detectors (TOF,TRD, etc. have to develop their specific codes)
2831  //
2832  //  Input: none
2833  //  Return: kTRUE if all operations have been done properly, kFALSE otherwise
2834  //
2835  Bool_t ret=kFALSE;
2836  //for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
2837  for (Int_t iDet = 0; iDet < 1; iDet++) { // for the time being only ITS
2838    //if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
2839    if(fTracker[iDet]) {
2840       AliPlaneEff *planeeff=fTracker[iDet]->GetPlaneEff();
2841       TString name=planeeff->GetName();
2842       name+=".root";
2843       TFile* pefile = TFile::Open(name, "RECREATE");
2844       ret=(Bool_t)planeeff->Write();
2845       pefile->Close();
2846       if(planeeff->GetCreateHistos()) {
2847         TString hname=planeeff->GetName();
2848         hname+="Histo.root";
2849         ret*=planeeff->WriteHistosToFile(hname,"RECREATE");
2850       }
2851    }
2852  }
2853  return ret;
2854 }
2855 //_____________________________________________________________________________
2856 Bool_t AliReconstruction::InitPlaneEff() {
2857 //
2858  // Here execute all the necessary operations, before of the tracking phase,
2859  // for the evaluation of PlaneEfficiencies, in case required for some detectors.
2860  // E.g., read from a DataBase file a first evaluation of the PlaneEfficiency 
2861  // which should be updated/recalculated.
2862  //
2863  // This Preliminary version will work only FOR ITS !!!!!
2864  // other detectors (TOF,TRD, etc. have to develop their specific codes)
2865  //
2866  //  Input: none
2867  //  Return: kTRUE if all operations have been done properly, kFALSE otherwise
2868  //
2869  AliWarning(Form("Implementation of this method not yet done !! Method return kTRUE"));
2870  return kTRUE;
2871 }
2872
2873 //_____________________________________________________________________________
2874 Bool_t AliReconstruction::InitAliEVE()
2875 {
2876   // This method should be called only in case 
2877   // AliReconstruction is run
2878   // within the alieve environment.
2879   // It will initialize AliEVE in a way
2880   // so that it can visualize event processed
2881   // by AliReconstruction.
2882   // The return flag shows whenever the
2883   // AliEVE initialization was successful or not.
2884
2885   TString macroStr;
2886   macroStr.Form("%s/EVE/macros/alieve_online.C",gSystem->ExpandPathName("$ALICE_ROOT"));
2887   AliInfo(Form("Loading AliEVE macro: %s",macroStr.Data()));
2888   if (gROOT->LoadMacro(macroStr.Data()) != 0) return kFALSE;
2889
2890   gROOT->ProcessLine("if (!AliEveEventManager::GetMaster()){new AliEveEventManager();AliEveEventManager::GetMaster()->AddNewEventCommand(\"alieve_online_on_new_event()\");gEve->AddEvent(AliEveEventManager::GetMaster());};");
2891   gROOT->ProcessLine("alieve_online_init()");
2892
2893   return kTRUE;
2894 }
2895   
2896 //_____________________________________________________________________________
2897 void AliReconstruction::RunAliEVE()
2898 {
2899   // Runs AliEVE visualisation of
2900   // the current event.
2901   // Should be executed only after
2902   // successful initialization of AliEVE.
2903
2904   AliInfo("Running AliEVE...");
2905   gROOT->ProcessLine(Form("AliEveEventManager::GetMaster()->SetEvent((AliRunLoader*)%p,(AliRawReader*)%p,(AliESDEvent*)%p);",fRunLoader,fRawReader,fesd));
2906   gSystem->Run();
2907 }
2908
2909 //_____________________________________________________________________________
2910 Bool_t AliReconstruction::SetRunQA(TString detAndAction) 
2911 {
2912         // Allows to run QA for a selected set of detectors
2913         // and a selected set of tasks among RAWS, RECPOINTS and ESDS
2914         // all selected detectors run the same selected tasks
2915         
2916         if (!detAndAction.Contains(":")) {
2917                 AliError( Form("%s is a wrong syntax, use \"DetectorList:ActionList\" \n", detAndAction.Data()) ) ;
2918                 fRunQA = kFALSE ;
2919                 return kFALSE ;                 
2920         }
2921         Int_t colon = detAndAction.Index(":") ; 
2922         fQADetectors = detAndAction(0, colon) ; 
2923         if (fQADetectors.Contains("ALL") )
2924                 fQADetectors = fFillESD ; 
2925                 fQATasks   = detAndAction(colon+1, detAndAction.Sizeof() ) ; 
2926         if (fQATasks.Contains("ALL") ) {
2927                 fQATasks = Form("%d %d %d", AliQA::kRAWS, AliQA::kRECPOINTS, AliQA::kESDS) ; 
2928         } else {
2929                 fQATasks.ToUpper() ; 
2930                 TString tempo("") ; 
2931                 if ( fQATasks.Contains("RAW") ) 
2932                         tempo = Form("%d ", AliQA::kRAWS) ; 
2933                 if ( fQATasks.Contains("RECPOINT") ) 
2934                         tempo += Form("%d ", AliQA::kRECPOINTS) ; 
2935                 if ( fQATasks.Contains("ESD") ) 
2936                         tempo += Form("%d ", AliQA::kESDS) ; 
2937                 fQATasks = tempo ; 
2938                 if (fQATasks.IsNull()) {
2939                         AliInfo("No QA requested\n")  ;
2940                         fRunQA = kFALSE ;
2941                         return kTRUE ; 
2942                 }
2943         }       
2944         TString tempo(fQATasks) ; 
2945         tempo.ReplaceAll(Form("%d", AliQA::kRAWS), AliQA::GetTaskName(AliQA::kRAWS))    ;
2946         tempo.ReplaceAll(Form("%d", AliQA::kRECPOINTS), AliQA::GetTaskName(AliQA::kRECPOINTS)) ;        
2947         tempo.ReplaceAll(Form("%d", AliQA::kESDS), AliQA::GetTaskName(AliQA::kESDS)) ;  
2948         AliInfo( Form("QA will be done on \"%s\" for \"%s\"\n", fQADetectors.Data(), tempo.Data()) ) ;  
2949         fRunQA = kTRUE ;
2950         return kTRUE; 
2951
2952
2953 //_____________________________________________________________________________
2954 Bool_t AliReconstruction::InitRecoParams() 
2955 {
2956   // The method accesses OCDB and retrieves all
2957   // the available reco-param objects from there.
2958
2959   Bool_t isOK = kTRUE;
2960
2961   TString detStr = fLoadCDB;
2962   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
2963
2964     if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
2965
2966     if (fRecoParam.GetDetRecoParamArray(iDet)) {
2967       AliInfo(Form("Using custom reconstruction parameters for detector %s",fgkDetectorName[iDet]));
2968       continue;
2969     }
2970
2971     AliInfo(Form("Loading reconstruction parameter objects for detector %s",fgkDetectorName[iDet]));
2972   
2973     AliCDBPath path(fgkDetectorName[iDet],"Calib","RecoParam");
2974     AliCDBEntry *entry=AliCDBManager::Instance()->Get(path.GetPath());
2975     if(!entry){ 
2976       AliWarning(Form("Couldn't find RecoParam entry in OCDB for detector %s",fgkDetectorName[iDet]));
2977       isOK = kFALSE;
2978     }
2979     else {
2980       TObject *recoParamObj = entry->GetObject();
2981       if (dynamic_cast<TObjArray*>(recoParamObj)) {
2982         // The detector has a normal TobjArray of AliDetectorRecoParam objects
2983         // Registering them in AliRecoParam
2984         fRecoParam.AddDetRecoParamArray(iDet,dynamic_cast<TObjArray*>(recoParamObj));
2985       }
2986       else if (dynamic_cast<AliDetectorRecoParam*>(recoParamObj)) {
2987         // The detector has only onse set of reco parameters
2988         // Registering it in AliRecoParam
2989         AliInfo(Form("Single set of reconstruction parameters found for detector %s",fgkDetectorName[iDet]));
2990         dynamic_cast<AliDetectorRecoParam*>(recoParamObj)->SetAsDefault();
2991         fRecoParam.AddDetRecoParam(iDet,dynamic_cast<AliDetectorRecoParam*>(recoParamObj));
2992       }
2993       else {
2994         AliError(Form("No valid RecoParam object found in the OCDB for detector %s",fgkDetectorName[iDet]));
2995         isOK = kFALSE;
2996       }
2997       entry->SetOwner(0);
2998       AliCDBManager::Instance()->UnloadFromCache(path.GetPath());
2999     }
3000   }
3001
3002   if (AliDebugLevel() > 0) fRecoParam.Print();
3003
3004   return isOK;
3005 }
3006
3007 //_____________________________________________________________________________
3008 Bool_t AliReconstruction::GetEventInfo() 
3009 {
3010   // Fill the event info object
3011   // ...
3012   AliCodeTimerAuto("")
3013
3014   AliCentralTrigger *aCTP = NULL;
3015   if (fRawReader) {
3016     fEventInfo.SetEventType(fRawReader->GetType());
3017
3018     ULong64_t mask = fRawReader->GetClassMask();
3019     fEventInfo.SetTriggerMask(mask);
3020     UInt_t clmask = fRawReader->GetDetectorPattern()[0];
3021     fEventInfo.SetTriggerCluster(AliDAQ::ListOfTriggeredDetectors(clmask));
3022
3023     aCTP = new AliCentralTrigger();
3024     TString configstr("");
3025     if (!aCTP->LoadConfiguration(configstr)) { // Load CTP config from OCDB
3026       AliError("No trigger configuration found in OCDB! The trigger configuration information will not be used!");
3027       delete aCTP;
3028       return kFALSE;
3029     }
3030     aCTP->SetClassMask(mask);
3031     aCTP->SetClusterMask(clmask);
3032   }
3033   else {
3034     fEventInfo.SetEventType(AliRawEventHeaderBase::kPhysicsEvent);
3035
3036     if (fRunLoader && (!fRunLoader->LoadTrigger())) {
3037       aCTP = fRunLoader->GetTrigger();
3038       fEventInfo.SetTriggerMask(aCTP->GetClassMask());
3039       fEventInfo.SetTriggerCluster(AliDAQ::ListOfTriggeredDetectors(aCTP->GetClusterMask()));
3040     }
3041     else {
3042       AliWarning("No trigger can be loaded! The trigger information will not be used!");
3043       return kFALSE;
3044     }
3045   }
3046
3047   AliTriggerConfiguration *config = aCTP->GetConfiguration();
3048   if (!config) {
3049     AliError("No trigger configuration has been found! The trigger configuration information will not be used!");
3050     if (fRawReader) delete aCTP;
3051     return kFALSE;
3052   }
3053
3054   UChar_t clustmask = 0;
3055   TString trclasses;
3056   ULong64_t trmask = fEventInfo.GetTriggerMask();
3057   const TObjArray& classesArray = config->GetClasses();
3058   Int_t nclasses = classesArray.GetEntriesFast();
3059   for( Int_t iclass=0; iclass < nclasses; iclass++ ) {
3060     AliTriggerClass* trclass = (AliTriggerClass*)classesArray.At(iclass);
3061     if (trclass) {
3062       Int_t trindex = TMath::Nint(TMath::Log2(trclass->GetMask()));
3063       fesd->SetTriggerClass(trclass->GetName(),trindex);
3064       if (fRawReader) fRawReader->LoadTriggerClass(trclass->GetName(),trindex);
3065       if (trmask & (1 << trindex)) {
3066         trclasses += " ";
3067         trclasses += trclass->GetName();
3068         trclasses += " ";
3069         clustmask |= trclass->GetCluster()->GetClusterMask();
3070       }
3071     }
3072   }
3073   fEventInfo.SetTriggerClasses(trclasses);
3074
3075   // Set the information in ESD
3076   fesd->SetTriggerMask(trmask);
3077   fesd->SetTriggerCluster(clustmask);
3078
3079   if (!aCTP->CheckTriggeredDetectors()) {
3080     if (fRawReader) delete aCTP;
3081     return kFALSE;
3082   }    
3083
3084   if (fRawReader) delete aCTP;
3085
3086   // We have to fill also the HLT decision here!!
3087   // ...
3088
3089   return kTRUE;
3090 }
3091
3092 const char *AliReconstruction::MatchDetectorList(const char *detectorList, UInt_t detectorMask)
3093 {
3094   // Match the detector list found in the rec.C or the default 'ALL'
3095   // to the list found in the GRP (stored there by the shuttle PP which
3096   // gets the information from ECS)
3097   static TString resultList;
3098   TString detList = detectorList;
3099
3100   resultList = "";
3101
3102   for(Int_t iDet = 0; iDet < (AliDAQ::kNDetectors-1); iDet++) {
3103     if ((detectorMask >> iDet) & 0x1) {
3104       TString det = AliDAQ::OfflineModuleName(iDet);
3105       if ((detList.CompareTo("ALL") == 0) ||
3106           ((detList.BeginsWith("ALL ") ||
3107             detList.EndsWith(" ALL") ||
3108             detList.Contains(" ALL ")) &&
3109            !(detList.BeginsWith("-"+det+" ") ||
3110              detList.EndsWith(" -"+det) ||
3111              detList.Contains(" -"+det+" "))) ||
3112           (detList.CompareTo(det) == 0) ||
3113           detList.BeginsWith(det+" ") ||
3114           detList.EndsWith(" "+det) ||
3115           detList.Contains( " "+det+" " )) {
3116         if (!resultList.EndsWith(det + " ")) {
3117           resultList += det;
3118           resultList += " ";
3119         }
3120       }        
3121     }
3122   }
3123
3124   // HLT
3125   if ((detectorMask >> AliDAQ::kHLTId) & 0x1) {
3126     TString hltDet = AliDAQ::OfflineModuleName(AliDAQ::kNDetectors-1);
3127     if ((detList.CompareTo("ALL") == 0) ||
3128         ((detList.BeginsWith("ALL ") ||
3129           detList.EndsWith(" ALL") ||
3130           detList.Contains(" ALL ")) &&
3131          !(detList.BeginsWith("-"+hltDet+" ") ||
3132            detList.EndsWith(" -"+hltDet) ||
3133            detList.Contains(" -"+hltDet+" "))) ||
3134         (detList.CompareTo(hltDet) == 0) ||
3135         detList.BeginsWith(hltDet+" ") ||
3136         detList.EndsWith(" "+hltDet) ||
3137         detList.Contains( " "+hltDet+" " )) {
3138       resultList += hltDet;
3139     }
3140   }
3141
3142   return resultList.Data();
3143
3144 }
3145
3146 //______________________________________________________________________________
3147 void AliReconstruction::Abort(const char *method, EAbort what)
3148 {
3149   // Abort processing. If what = kAbortProcess, the Process() loop will be
3150   // aborted. If what = kAbortFile, the current file in a chain will be
3151   // aborted and the processing will continue with the next file, if there
3152   // is no next file then Process() will be aborted. Abort() can also  be
3153   // called from Begin(), SlaveBegin(), Init() and Notify(). After abort
3154   // the SlaveTerminate() and Terminate() are always called. The abort flag
3155   // can be checked in these methods using GetAbort().
3156   //
3157   // The method is overwritten in AliReconstruction for better handling of
3158   // reco specific errors 
3159
3160   if (!fStopOnError) return;
3161
3162   CleanUp();
3163
3164   TString whyMess = method;
3165   whyMess += " failed! Aborting...";
3166
3167   AliError(whyMess.Data());
3168
3169   fAbort = what;
3170   TString mess = "Abort";
3171   if (fAbort == kAbortProcess)
3172     mess = "AbortProcess";
3173   else if (fAbort == kAbortFile)
3174     mess = "AbortFile";
3175
3176   Info(mess, whyMess.Data());
3177 }
3178