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