]> git.uio.no Git - u/mrichter/AliRoot.git/blob - STEER/AliReconstruction.cxx
Modified trackleting: AliMultiplicity stores info if the clusters
[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 <TArrayD.h>
112 #include <TArrayF.h>
113 #include <TArrayS.h>
114 #include <TChain.h>
115 #include <TFile.h>
116 #include <TGeoGlobalMagField.h>
117 #include <TGeoManager.h>
118 #include <TList.h>
119 #include <TLorentzVector.h>
120 #include <TMap.h>
121 #include <TObjArray.h>
122 #include <TPRegexp.h>
123 #include <TParameter.h>
124 #include <TPluginManager.h>
125 #include <TProof.h>
126 #include <TProofOutputFile.h>
127 #include <TROOT.h>
128 #include <TSystem.h>
129 #include <THashTable.h>
130 #include <TGrid.h>
131 #include <TMessage.h>
132 #include <TUrl.h>
133
134 #include "AliAlignObj.h"
135 #include "AliCDBEntry.h"
136 #include "AliCDBManager.h"
137 #include "AliCDBStorage.h"
138 #include "AliCTPRawStream.h"
139 #include "AliCascadeVertexer.h"
140 #include "AliCentralTrigger.h"
141 #include "AliCodeTimer.h"
142 #include "AliDAQ.h"
143 #include "AliDetectorRecoParam.h"
144 #include "AliESDCaloCells.h"
145 #include "AliESDCaloCluster.h"
146 #include "AliESDEvent.h"
147 #include "AliESDMuonTrack.h"
148 #include "AliESDPmdTrack.h"
149 #include "AliESDTagCreator.h"
150 #include "AliESDVertex.h"
151 #include "AliESDcascade.h"
152 #include "AliESDfriend.h"
153 #include "AliESDkink.h"
154 #include "AliESDpid.h"
155 #include "AliESDtrack.h"
156 #include "AliESDtrack.h"
157 #include "AliEventInfo.h"
158 #include "AliGRPObject.h"
159 #include "AliGRPRecoParam.h"
160 #include "AliGenEventHeader.h"
161 #include "AliGeomManager.h"
162 #include "AliGlobalQADataMaker.h" 
163 #include "AliHeader.h"
164 #include "AliLog.h"
165 #include "AliMagF.h"
166 #include "AliMultiplicity.h"
167 #include "AliPID.h"
168 #include "AliPlaneEff.h"
169 #include "AliQAv1.h"
170 #include "AliQADataMakerRec.h" 
171 #include "AliQAManager.h"
172 #include "AliRawVEvent.h"
173 #include "AliRawEventHeaderBase.h"
174 #include "AliRawHLTManager.h"
175 #include "AliRawReaderDate.h"
176 #include "AliRawReaderFile.h"
177 #include "AliRawReaderRoot.h"
178 #include "AliReconstruction.h"
179 #include "AliReconstructor.h"
180 #include "AliRun.h"
181 #include "AliRunInfo.h"
182 #include "AliRunLoader.h"
183 #include "AliSysInfo.h" // memory snapshots
184 #include "AliTrackPointArray.h"
185 #include "AliTracker.h"
186 #include "AliTriggerClass.h"
187 #include "AliTriggerCluster.h"
188 #include "AliTriggerIR.h"
189 #include "AliTriggerConfiguration.h"
190 #include "AliV0vertexer.h"
191 #include "AliVertexer.h"
192 #include "AliTrackleter.h"
193 #include "AliVertexerTracks.h"
194 #include "AliTriggerRunScalers.h"
195 #include "AliCTPTimeParams.h" 
196 #include "AliESDHLTDecision.h"
197 #include "AliTriggerInput.h"
198 #include "AliLHCData.h"
199 ClassImp(AliReconstruction)
200
201 //_____________________________________________________________________________
202 const char* AliReconstruction::fgkDetectorName[AliReconstruction::kNDetectors] = {"ITS", "TPC", "TRD", "TOF", "PHOS", "HMPID", "EMCAL", "MUON", "FMD", "ZDC", "PMD", "T0", "VZERO", "ACORDE", "HLT"};
203
204 //_____________________________________________________________________________
205 AliReconstruction::AliReconstruction(const char* gAliceFilename) :
206   TSelector(),
207   fRunVertexFinder(kTRUE),
208   fRunVertexFinderTracks(kTRUE),
209   fRunHLTTracking(kFALSE),
210   fRunMuonTracking(kFALSE),
211   fRunV0Finder(kTRUE),
212   fRunCascadeFinder(kTRUE),
213   fRunMultFinder(kTRUE),
214   fStopOnError(kTRUE),
215   fWriteAlignmentData(kFALSE),
216   fWriteESDfriend(kFALSE),
217   fFillTriggerESD(kTRUE),
218
219   fCleanESD(kTRUE),
220   fV0DCAmax(3.),
221   fV0CsPmin(0.),
222   fDmax(50.),
223   fZmax(50.),
224
225   fRunLocalReconstruction("ALL"),
226   fRunTracking("ALL"),
227   fFillESD("ALL"),
228   fLoadCDB(""),
229   fUseTrackingErrorsForAlignment(""),
230   fGAliceFileName(gAliceFilename),
231   fRawInput(""),
232   fESDOutput(""),
233   fProofOutputFileName(""),
234   fProofOutputLocation(""),
235   fProofOutputDataset(kFALSE),
236   fProofOutputArchive(""),
237   fEquipIdMap(""),
238   fFirstEvent(0),
239   fLastEvent(-1),
240   fNumberOfEventsPerFile((UInt_t)-1),
241   fOptions(),
242   fLoadAlignFromCDB(kTRUE),
243   fLoadAlignData("ALL"),
244   fUseHLTData(),
245   fRunInfo(NULL),
246   fEventInfo(),
247   fRunScalers(NULL),
248   fCTPTimeParams(NULL),  
249
250   fRunLoader(NULL),
251   fRawReader(NULL),
252   fParentRawReader(NULL),
253
254   fRecoParam(),
255
256   fSPDTrackleter(NULL),
257
258   fDiamondProfileSPD(NULL),
259   fDiamondProfile(NULL),
260   fDiamondProfileTPC(NULL),
261   fListOfCosmicTriggers(NULL),
262   
263   fGRPData(NULL),
264
265   fAlignObjArray(NULL),
266   fCDBUri(),
267   fQARefUri(),
268   fSpecCDBUri(), 
269   fInitCDBCalled(kFALSE),
270   fSetRunNumberFromDataCalled(kFALSE),
271   fQADetectors("ALL"), 
272   fQATasks("ALL"), 
273   fRunQA(kTRUE),  
274   fRunGlobalQA(kTRUE),
275   fSameQACycle(kFALSE),
276   fInitQACalled(kFALSE), 
277   fWriteQAExpertData(kTRUE), 
278   fRunPlaneEff(kFALSE),
279
280   fesd(NULL),
281   fhltesd(NULL),
282   fesdf(NULL),
283   ffile(NULL),
284   ffileF(NULL),
285   ftree(NULL),
286   ftreeF(NULL),
287   fhlttree(NULL),
288   ftVertexer(NULL),
289   fIsNewRunLoader(kFALSE),
290   fRunAliEVE(kFALSE),
291   fChain(NULL)
292 {
293 // create reconstruction object with default parameters
294   gGeoManager = NULL;
295   
296   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
297     fReconstructor[iDet] = NULL;
298     fLoader[iDet] = NULL;
299     fTracker[iDet] = NULL;
300   }
301   for (Int_t iDet = 0; iDet < AliQAv1::kNDET; iDet++) {
302     fQACycles[iDet] = 999999 ;
303     fQAWriteExpert[iDet] = kFALSE ; 
304   }
305   fBeamInt[0][0]=fBeamInt[0][1]=fBeamInt[1][0]=fBeamInt[1][1] = -1;
306
307   AliPID pid;
308 }
309
310 //_____________________________________________________________________________
311 AliReconstruction::AliReconstruction(const AliReconstruction& rec) :
312   TSelector(),
313   fRunVertexFinder(rec.fRunVertexFinder),
314   fRunVertexFinderTracks(rec.fRunVertexFinderTracks),
315   fRunHLTTracking(rec.fRunHLTTracking),
316   fRunMuonTracking(rec.fRunMuonTracking),
317   fRunV0Finder(rec.fRunV0Finder),
318   fRunCascadeFinder(rec.fRunCascadeFinder),
319   fRunMultFinder(rec.fRunMultFinder),
320   fStopOnError(rec.fStopOnError),
321   fWriteAlignmentData(rec.fWriteAlignmentData),
322   fWriteESDfriend(rec.fWriteESDfriend),
323   fFillTriggerESD(rec.fFillTriggerESD),
324
325   fCleanESD(rec.fCleanESD),
326   fV0DCAmax(rec.fV0DCAmax),
327   fV0CsPmin(rec.fV0CsPmin),
328   fDmax(rec.fDmax),
329   fZmax(rec.fZmax),
330
331   fRunLocalReconstruction(rec.fRunLocalReconstruction),
332   fRunTracking(rec.fRunTracking),
333   fFillESD(rec.fFillESD),
334   fLoadCDB(rec.fLoadCDB),
335   fUseTrackingErrorsForAlignment(rec.fUseTrackingErrorsForAlignment),
336   fGAliceFileName(rec.fGAliceFileName),
337   fRawInput(rec.fRawInput),
338   fESDOutput(rec.fESDOutput),
339   fProofOutputFileName(rec.fProofOutputFileName),
340   fProofOutputLocation(rec.fProofOutputLocation),
341   fProofOutputDataset(rec.fProofOutputDataset),
342   fProofOutputArchive(rec.fProofOutputArchive),
343   fEquipIdMap(rec.fEquipIdMap),
344   fFirstEvent(rec.fFirstEvent),
345   fLastEvent(rec.fLastEvent),
346   fNumberOfEventsPerFile(rec.fNumberOfEventsPerFile),
347   fOptions(),
348   fLoadAlignFromCDB(rec.fLoadAlignFromCDB),
349   fLoadAlignData(rec.fLoadAlignData),
350   fUseHLTData(rec.fUseHLTData),
351   fRunInfo(NULL),
352   fEventInfo(),
353   fRunScalers(NULL),
354   fCTPTimeParams(NULL),
355
356   fRunLoader(NULL),
357   fRawReader(NULL),
358   fParentRawReader(NULL),
359
360   fRecoParam(rec.fRecoParam),
361
362   fSPDTrackleter(NULL),
363
364   fDiamondProfileSPD(rec.fDiamondProfileSPD),
365   fDiamondProfile(rec.fDiamondProfile),
366   fDiamondProfileTPC(rec.fDiamondProfileTPC),
367   fListOfCosmicTriggers(NULL),
368   
369   fGRPData(NULL),
370
371   fAlignObjArray(rec.fAlignObjArray),
372   fCDBUri(rec.fCDBUri),
373   fQARefUri(rec.fQARefUri),
374   fSpecCDBUri(), 
375   fInitCDBCalled(rec.fInitCDBCalled),
376   fSetRunNumberFromDataCalled(rec.fSetRunNumberFromDataCalled),
377   fQADetectors(rec.fQADetectors), 
378   fQATasks(rec.fQATasks), 
379   fRunQA(rec.fRunQA),  
380   fRunGlobalQA(rec.fRunGlobalQA),
381   fSameQACycle(rec.fSameQACycle),
382   fInitQACalled(rec.fInitQACalled),
383   fWriteQAExpertData(rec.fWriteQAExpertData), 
384   fRunPlaneEff(rec.fRunPlaneEff),
385
386   fesd(NULL),
387   fhltesd(NULL),
388   fesdf(NULL),
389   ffile(NULL),
390   ffileF(NULL),
391   ftree(NULL),
392   ftreeF(NULL),
393   fhlttree(NULL),
394   ftVertexer(NULL),
395   fIsNewRunLoader(rec.fIsNewRunLoader),
396   fRunAliEVE(kFALSE),
397   fChain(NULL)
398 {
399 // copy constructor
400
401   for (Int_t i = 0; i < rec.fOptions.GetEntriesFast(); i++) {
402     if (rec.fOptions[i]) fOptions.Add(rec.fOptions[i]->Clone());
403   }
404   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
405     fReconstructor[iDet] = NULL;
406     fLoader[iDet] = NULL;
407     fTracker[iDet] = NULL;
408   }  
409   
410   for (Int_t iDet = 0; iDet < AliQAv1::kNDET; iDet++) {
411     fQACycles[iDet] = rec.fQACycles[iDet];
412     fQAWriteExpert[iDet] = rec.fQAWriteExpert[iDet] ; 
413   }
414
415   for (Int_t i = 0; i < rec.fSpecCDBUri.GetEntriesFast(); i++) {
416     if (rec.fSpecCDBUri[i]) fSpecCDBUri.Add(rec.fSpecCDBUri[i]->Clone());
417   }
418
419   for (int i=2;i--;) for (int j=2;j--;) fBeamInt[i][j] = rec.fBeamInt[i][j];
420
421 }
422
423 //_____________________________________________________________________________
424 AliReconstruction& AliReconstruction::operator = (const AliReconstruction& rec)
425 {
426 // assignment operator
427 // Used in PROOF mode
428 // Be very careful while modifing it!
429 // Simple rules to follow:
430 // for persistent data members - use their assignment operators
431 // for non-persistent ones - do nothing or take the default values from constructor
432 // TSelector members should not be touched
433   if(&rec == this) return *this;
434
435   fRunVertexFinder       = rec.fRunVertexFinder;
436   fRunVertexFinderTracks = rec.fRunVertexFinderTracks;
437   fRunHLTTracking        = rec.fRunHLTTracking;
438   fRunMuonTracking       = rec.fRunMuonTracking;
439   fRunV0Finder           = rec.fRunV0Finder;
440   fRunCascadeFinder      = rec.fRunCascadeFinder;
441   fRunMultFinder         = rec.fRunMultFinder;
442   fStopOnError           = rec.fStopOnError;
443   fWriteAlignmentData    = rec.fWriteAlignmentData;
444   fWriteESDfriend        = rec.fWriteESDfriend;
445   fFillTriggerESD        = rec.fFillTriggerESD;
446
447   fCleanESD  = rec.fCleanESD;
448   fV0DCAmax  = rec.fV0DCAmax;
449   fV0CsPmin  = rec.fV0CsPmin;
450   fDmax      = rec.fDmax;
451   fZmax      = rec.fZmax;
452
453   fRunLocalReconstruction        = rec.fRunLocalReconstruction;
454   fRunTracking                   = rec.fRunTracking;
455   fFillESD                       = rec.fFillESD;
456   fLoadCDB                       = rec.fLoadCDB;
457   fUseTrackingErrorsForAlignment = rec.fUseTrackingErrorsForAlignment;
458   fGAliceFileName                = rec.fGAliceFileName;
459   fRawInput                      = rec.fRawInput;
460   fESDOutput                     = rec.fESDOutput;
461   fProofOutputFileName           = rec.fProofOutputFileName;
462   fProofOutputLocation           = rec.fProofOutputLocation;
463   fProofOutputDataset            = rec.fProofOutputDataset;
464   fProofOutputArchive            = rec.fProofOutputArchive;
465   fEquipIdMap                    = rec.fEquipIdMap;
466   fFirstEvent                    = rec.fFirstEvent;
467   fLastEvent                     = rec.fLastEvent;
468   fNumberOfEventsPerFile         = rec.fNumberOfEventsPerFile;
469
470   for (Int_t i = 0; i < rec.fOptions.GetEntriesFast(); i++) {
471     if (rec.fOptions[i]) fOptions.Add(rec.fOptions[i]->Clone());
472   }
473
474   fLoadAlignFromCDB              = rec.fLoadAlignFromCDB;
475   fLoadAlignData                 = rec.fLoadAlignData;
476   fUseHLTData                    = rec.fUseHLTData;
477
478   delete fRunInfo; fRunInfo = NULL;
479   if (rec.fRunInfo) fRunInfo = new AliRunInfo(*rec.fRunInfo);
480
481   fEventInfo                     = rec.fEventInfo;
482
483   delete fRunScalers; fRunScalers = NULL;
484   if (rec.fRunScalers) fRunScalers = new AliTriggerRunScalers(*rec.fRunScalers); 
485
486   delete fCTPTimeParams; fCTPTimeParams = NULL;
487   if (rec.fCTPTimeParams) fCTPTimeParams = new AliCTPTimeParams(*rec.fCTPTimeParams);
488
489   fRunLoader       = NULL;
490   fRawReader       = NULL;
491   fParentRawReader = NULL;
492
493   fRecoParam = rec.fRecoParam;
494
495   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
496     delete fReconstructor[iDet]; fReconstructor[iDet] = NULL;
497     delete fLoader[iDet]; fLoader[iDet] = NULL;
498     delete fTracker[iDet]; fTracker[iDet] = NULL;
499   }
500   
501   for (Int_t iDet = 0; iDet < AliQAv1::kNDET; iDet++) {
502     fQACycles[iDet] = rec.fQACycles[iDet];
503     fQAWriteExpert[iDet] = rec.fQAWriteExpert[iDet] ;
504   } 
505
506   delete fSPDTrackleter; fSPDTrackleter = NULL;
507     
508   delete fDiamondProfileSPD; fDiamondProfileSPD = NULL;
509   if (rec.fDiamondProfileSPD) fDiamondProfileSPD = new AliESDVertex(*rec.fDiamondProfileSPD);
510   delete fDiamondProfile; fDiamondProfile = NULL;
511   if (rec.fDiamondProfile) fDiamondProfile = new AliESDVertex(*rec.fDiamondProfile);
512   delete fDiamondProfileTPC; fDiamondProfileTPC = NULL;
513   if (rec.fDiamondProfileTPC) fDiamondProfileTPC = new AliESDVertex(*rec.fDiamondProfileTPC);
514
515   delete fListOfCosmicTriggers; fListOfCosmicTriggers = NULL;
516   if (rec.fListOfCosmicTriggers) fListOfCosmicTriggers = (THashTable*)((rec.fListOfCosmicTriggers)->Clone());
517
518   delete fGRPData; fGRPData = NULL;
519   //  if (rec.fGRPData) fGRPData = (TMap*)((rec.fGRPData)->Clone());
520   if (rec.fGRPData) fGRPData = (AliGRPObject*)((rec.fGRPData)->Clone());
521
522   delete fAlignObjArray; fAlignObjArray = NULL;
523
524   fCDBUri        = "";
525   fQARefUri      = rec.fQARefUri;
526   fSpecCDBUri.Delete();
527   fInitCDBCalled               = rec.fInitCDBCalled;
528   fSetRunNumberFromDataCalled  = rec.fSetRunNumberFromDataCalled;
529   fQADetectors                 = rec.fQADetectors;
530   fQATasks                     = rec.fQATasks; 
531   fRunQA                       = rec.fRunQA;  
532   fRunGlobalQA                 = rec.fRunGlobalQA;
533   fSameQACycle                 = rec.fSameQACycle;
534   fInitQACalled                = rec.fInitQACalled;
535   fWriteQAExpertData           = rec.fWriteQAExpertData;
536   fRunPlaneEff                 = rec.fRunPlaneEff;
537   for (int i=2;i--;) for (int j=2;j--;) fBeamInt[i][j] = rec.fBeamInt[i][j];
538   fesd     = NULL;
539   fhltesd  = NULL;
540   fesdf    = NULL;
541   ffile    = NULL;
542   ffileF   = NULL;
543   ftree    = NULL;
544   ftreeF   = NULL;
545   fhlttree = NULL;
546   ftVertexer = NULL;
547   fIsNewRunLoader = rec.fIsNewRunLoader;
548   fRunAliEVE = kFALSE;
549   fChain = NULL;
550
551   return *this;
552 }
553
554 //_____________________________________________________________________________
555 AliReconstruction::~AliReconstruction()
556 {
557 // clean up
558
559   CleanUp();
560   if (fListOfCosmicTriggers) {
561     fListOfCosmicTriggers->Delete();
562     delete fListOfCosmicTriggers;
563   }
564   delete fGRPData;
565   delete fRunScalers;
566   delete fCTPTimeParams;
567   fOptions.Delete();
568   if (fAlignObjArray) {
569     fAlignObjArray->Delete();
570     delete fAlignObjArray;
571   }
572   fSpecCDBUri.Delete();
573
574   AliCodeTimer::Instance()->Print();
575 }
576
577 //_____________________________________________________________________________
578 void AliReconstruction::InitQA()
579 {
580   //Initialize the QA and start of cycle 
581   AliCodeTimerAuto("",0);
582   
583   if (fInitQACalled) return;
584   fInitQACalled = kTRUE;
585   
586   AliQAManager * qam = AliQAManager::QAManager(AliQAv1::kRECMODE) ; 
587   if (fWriteQAExpertData)
588     qam->SetWriteExpert() ; 
589  
590   if (qam->IsDefaultStorageSet()) {
591     AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
592     AliWarning("Default QA reference storage has been already set !");
593     AliWarning(Form("Ignoring the default storage declared in AliReconstruction: %s",fQARefUri.Data()));
594     AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
595     fQARefUri = qam->GetDefaultStorage()->GetURI();
596   } else {
597     if (fQARefUri.Length() > 0) {
598         AliDebug(2,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
599         AliDebug(2, Form("Default QA reference storage is set to: %s", fQARefUri.Data()));
600         AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
601       } else {
602         fQARefUri="local://$ALICE_ROOT/QAref";
603         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
604         AliWarning("Default QA refeference storage not yet set !!!!");
605         AliWarning(Form("Setting it now to: %s", fQARefUri.Data()));
606         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
607                 
608       }
609     qam->SetDefaultStorage(fQARefUri);
610   }
611   
612   if (fRunQA) {
613   qam->SetActiveDetectors(fQADetectors) ; 
614   for (Int_t det = 0 ; det < AliQAv1::kNDET ; det++) {
615     qam->SetCycleLength(AliQAv1::DETECTORINDEX_t(det), fQACycles[det]) ;  
616     qam->SetWriteExpert(AliQAv1::DETECTORINDEX_t(det)) ;
617   }
618   if (!fRawReader && !fInput && IsInTasks(AliQAv1::kRAWS))
619     fQATasks.ReplaceAll(Form("%d",AliQAv1::kRAWS), "") ;
620   qam->SetTasks(fQATasks) ; 
621   qam->InitQADataMaker(AliCDBManager::Instance()->GetRun()) ; 
622   }
623   if (fRunGlobalQA) {
624     Bool_t sameCycle = kFALSE ;
625     AliQADataMaker *qadm = qam->GetQADataMaker(AliQAv1::kGLOBAL);
626     AliInfo(Form("Initializing the global QA data maker"));
627     if (IsInTasks(AliQAv1::kRECPOINTS)) {
628       qadm->StartOfCycle(AliQAv1::kRECPOINTS, AliCDBManager::Instance()->GetRun(), sameCycle) ; 
629       TObjArray **arr=qadm->Init(AliQAv1::kRECPOINTS);
630       AliTracker::SetResidualsArray(arr);
631       sameCycle = kTRUE ; 
632     }
633     if (IsInTasks(AliQAv1::kESDS)) {
634       qadm->StartOfCycle(AliQAv1::kESDS, AliCDBManager::Instance()->GetRun(), sameCycle) ; 
635       qadm->Init(AliQAv1::kESDS);
636     }
637   }
638     AliSysInfo::AddStamp("InitQA") ; 
639 }
640
641 //_____________________________________________________________________________
642 void AliReconstruction::MergeQA(const char *fileName)
643 {
644   //Initialize the QA and start of cycle 
645   AliCodeTimerAuto("",0) ;
646   AliQAManager::QAManager()->Merge(AliCDBManager::Instance()->GetRun(),fileName) ; 
647   AliSysInfo::AddStamp("MergeQA") ; 
648 }
649   
650 //_____________________________________________________________________________
651 void AliReconstruction::InitCDB()
652 {
653 // activate a default CDB storage
654 // First check if we have any CDB storage set, because it is used 
655 // to retrieve the calibration and alignment constants
656   AliCodeTimerAuto("",0);
657
658   if (fInitCDBCalled) return;
659   fInitCDBCalled = kTRUE;
660
661   AliCDBManager* man = AliCDBManager::Instance();
662   if (man->IsDefaultStorageSet())
663   {
664     AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
665     AliWarning("Default CDB storage has been already set !");
666     AliWarning(Form("Ignoring the default storage declared in AliReconstruction: %s",fCDBUri.Data()));
667     AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
668     fCDBUri = man->GetDefaultStorage()->GetURI();
669   }
670   else {
671     if (fCDBUri.Length() > 0) 
672     {
673         AliDebug(2,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
674         AliDebug(2, Form("Default CDB storage is set to: %s", fCDBUri.Data()));
675         AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
676         man->SetDefaultStorage(fCDBUri);
677     } 
678     else if (!man->GetRaw()){
679         fCDBUri="local://$ALICE_ROOT/OCDB";
680         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
681         AliWarning("Default CDB storage not yet set !!!!");
682         AliWarning(Form("Setting it now to: %s", fCDBUri.Data()));
683         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
684         man->SetDefaultStorage(fCDBUri);
685     }
686     else {    
687         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
688         AliWarning("Default storage will be set after setting the Run Number!!!");
689         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");                    
690     }
691   }
692
693   // Now activate the detector specific CDB storage locations
694   for (Int_t i = 0; i < fSpecCDBUri.GetEntriesFast(); i++) {
695     TObject* obj = fSpecCDBUri[i];
696     if (!obj) continue;
697     AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
698     AliDebug(2, Form("Specific CDB storage for %s is set to: %s",obj->GetName(),obj->GetTitle()));
699     AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
700     man->SetSpecificStorage(obj->GetName(), obj->GetTitle());
701   }
702   AliSysInfo::AddStamp("InitCDB");
703 }
704
705 //_____________________________________________________________________________
706 void AliReconstruction::SetDefaultStorage(const char* uri) {
707 // Store the desired default CDB storage location
708 // Activate it later within the Run() method
709
710   fCDBUri = uri;
711
712 }
713
714 //_____________________________________________________________________________
715 void AliReconstruction::SetQARefDefaultStorage(const char* uri) {
716   // Store the desired default CDB storage location
717   // Activate it later within the Run() method
718   
719   fQARefUri = uri;
720   AliQAv1::SetQARefStorage(fQARefUri.Data()) ;
721   
722 }
723 //_____________________________________________________________________________
724 void AliReconstruction::SetSpecificStorage(const char* calibType, const char* uri) {
725 // Store a detector-specific CDB storage location
726 // Activate it later within the Run() method
727
728   AliCDBPath aPath(calibType);
729   if(!aPath.IsValid()){
730         // if calibType is not wildcard but it is a valid detector, add "/*" to make it a valid path
731         for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
732                 if(!strcmp(calibType, fgkDetectorName[iDet])) {
733                         aPath.SetPath(Form("%s/*", calibType));
734                         AliInfo(Form("Path for specific storage set to %s", aPath.GetPath().Data()));
735                         break;
736                 }
737         }
738         if(!aPath.IsValid()){
739                 AliError(Form("Not a valid path or detector: %s", calibType));
740                 return;
741         }
742   }
743
744 //  // check that calibType refers to a "valid" detector name
745 //  Bool_t isDetector = kFALSE;
746 //  for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
747 //    TString detName = fgkDetectorName[iDet];
748 //    if(aPath.GetLevel0() == detName) {
749 //      isDetector = kTRUE;
750 //      break;
751 //    }
752 //  }
753 //
754 //  if(!isDetector) {
755 //      AliError(Form("Not a valid detector: %s", aPath.GetLevel0().Data()));
756 //      return;
757 //  }
758
759   TObject* obj = fSpecCDBUri.FindObject(aPath.GetPath().Data());
760   if (obj) fSpecCDBUri.Remove(obj);
761   fSpecCDBUri.Add(new TNamed(aPath.GetPath().Data(), uri));
762
763 }
764
765 //_____________________________________________________________________________
766 Bool_t AliReconstruction::SetRunNumberFromData()
767 {
768   // The method is called in Run() in order
769   // to set a correct run number.
770   // In case of raw data reconstruction the
771   // run number is taken from the raw data header
772
773   if (fSetRunNumberFromDataCalled) return kTRUE;
774   fSetRunNumberFromDataCalled = kTRUE;
775   
776   AliCDBManager* man = AliCDBManager::Instance();
777  
778   if(fRawReader) {
779     if(fRawReader->NextEvent()) {
780       if(man->GetRun() > 0) {
781         AliWarning("Run number is taken from raw-event header! Ignoring settings in AliCDBManager!");
782       } 
783       man->SetRun(fRawReader->GetRunNumber());
784       fRawReader->RewindEvents();
785     }
786     else {
787       if(man->GetRun() > 0) {
788         AliWarning("No raw-data events are found ! Using settings in AliCDBManager !");
789       }
790       else {
791         AliWarning("Neither raw events nor settings in AliCDBManager are found !");
792         return kFALSE;
793       }
794     }
795   }
796   else {
797     AliRunLoader *rl = AliRunLoader::Open(fGAliceFileName.Data());
798     if (!rl) {
799       AliError(Form("No run loader found in file %s", fGAliceFileName.Data()));
800       return kFALSE;
801     }
802     else {
803       rl->LoadHeader();
804       // read run number from gAlice
805       if(rl->GetHeader()) {
806         man->SetRun(rl->GetHeader()->GetRun());
807         rl->UnloadHeader();
808         delete rl;
809       }
810       else {
811         AliError("Neither run-loader header nor RawReader objects are found !");
812         delete rl;
813         return kFALSE;
814       }
815     }
816   }
817
818   man->Print();  
819   
820   return kTRUE;
821 }
822
823 //_____________________________________________________________________________
824 void AliReconstruction::SetCDBLock() {
825   // Set CDB lock: from now on it is forbidden to reset the run number
826   // or the default storage or to activate any further storage!
827   
828   AliCDBManager::Instance()->SetLock(1);
829 }
830
831 //_____________________________________________________________________________
832 Bool_t AliReconstruction::MisalignGeometry(const TString& detectors)
833 {
834   // Read the alignment objects from CDB.
835   // Each detector is supposed to have the
836   // alignment objects in DET/Align/Data CDB path.
837   // All the detector objects are then collected,
838   // sorted by geometry level (starting from ALIC) and
839   // then applied to the TGeo geometry.
840   // Finally an overlaps check is performed.
841
842   // Load alignment data from CDB and fill fAlignObjArray 
843   if(fLoadAlignFromCDB){
844         
845     TString detStr = detectors;
846     TString loadAlObjsListOfDets = "";
847     
848     for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
849       if(!IsSelected(fgkDetectorName[iDet], detStr)) continue;
850       if(!strcmp(fgkDetectorName[iDet],"HLT")) continue;
851       
852       if(AliGeomManager::GetNalignable(fgkDetectorName[iDet]) != 0)
853       {
854         loadAlObjsListOfDets += fgkDetectorName[iDet];
855         loadAlObjsListOfDets += " ";
856       }
857     } // end loop over detectors
858     
859     if(AliGeomManager::GetNalignable("GRP") != 0)
860       loadAlObjsListOfDets.Prepend("GRP "); //add alignment objects for non-sensitive modules
861     AliGeomManager::ApplyAlignObjsFromCDB(loadAlObjsListOfDets.Data());
862     AliCDBManager::Instance()->UnloadFromCache("*/Align/*");
863   }else{
864     // Check if the array with alignment objects was
865     // provided by the user. If yes, apply the objects
866     // to the present TGeo geometry
867     if (fAlignObjArray) {
868       if (gGeoManager && gGeoManager->IsClosed()) {
869         if (AliGeomManager::ApplyAlignObjsToGeom(*fAlignObjArray) == kFALSE) {
870           AliError("The misalignment of one or more volumes failed!"
871                    "Compare the list of simulated detectors and the list of detector alignment data!");
872           return kFALSE;
873         }
874       }
875       else {
876         AliError("Can't apply the misalignment! gGeoManager doesn't exist or it is still opened!");
877         return kFALSE;
878       }
879     }
880   }
881   
882   if (fAlignObjArray) {
883     fAlignObjArray->Delete();
884     delete fAlignObjArray; fAlignObjArray=NULL;
885   }
886
887   return kTRUE;
888 }
889
890 //_____________________________________________________________________________
891 void AliReconstruction::SetGAliceFile(const char* fileName)
892 {
893 // set the name of the galice file
894
895   fGAliceFileName = fileName;
896 }
897
898 //_____________________________________________________________________________
899 void AliReconstruction::SetInput(const char* input) 
900 {
901   // In case the input string starts with 'mem://', we run in an online mode
902   // and AliRawReaderDateOnline object is created. In all other cases a raw-data
903   // file is assumed. One can give as an input:
904   // mem://: - events taken from DAQ monitoring libs online
905   //  or
906   // mem://<filename> - emulation of the above mode (via DATE monitoring libs)
907   if (input) fRawInput = input;
908 }
909
910 //_____________________________________________________________________________
911 void AliReconstruction::SetOutput(const char* output) 
912 {
913   // Set the output ESD filename
914   // 'output' is a normalt ROOT url
915   // The method is used in case of raw-data reco with PROOF
916   if (output) fESDOutput = output;
917 }
918
919 //_____________________________________________________________________________
920 void AliReconstruction::SetOption(const char* detector, const char* option)
921 {
922 // set options for the reconstruction of a detector
923
924   TObject* obj = fOptions.FindObject(detector);
925   if (obj) fOptions.Remove(obj);
926   fOptions.Add(new TNamed(detector, option));
927 }
928
929 //_____________________________________________________________________________
930 void AliReconstruction::SetRecoParam(const char* detector, AliDetectorRecoParam *par)
931 {
932   // Set custom reconstruction parameters for a given detector
933   // Single set of parameters for all the events
934
935   // First check if the reco-params are global
936   if(!strcmp(detector, "GRP")) {
937     par->SetAsDefault();
938     fRecoParam.AddDetRecoParam(kNDetectors,par);
939     return;
940   }
941
942   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
943     if(!strcmp(detector, fgkDetectorName[iDet])) {
944       par->SetAsDefault();
945       fRecoParam.AddDetRecoParam(iDet,par);
946       break;
947     }
948   }
949
950 }
951
952 //_____________________________________________________________________________
953 Bool_t AliReconstruction::InitGRP() {
954   //------------------------------------
955   // Initialization of the GRP entry 
956   //------------------------------------
957   AliCDBEntry* entry = AliCDBManager::Instance()->Get("GRP/GRP/Data");
958
959   if (entry) {
960
961     TMap* m = dynamic_cast<TMap*>(entry->GetObject());  // old GRP entry
962
963     if (m) {
964        AliInfo("Found a TMap in GRP/GRP/Data, converting it into an AliGRPObject");
965        m->Print();
966        fGRPData = new AliGRPObject();
967        fGRPData->ReadValuesFromMap(m);
968     }
969
970     else {
971        AliInfo("Found an AliGRPObject in GRP/GRP/Data, reading it");
972        fGRPData = dynamic_cast<AliGRPObject*>(entry->GetObject());  // new GRP entry
973        entry->SetOwner(0);
974     }
975
976     //    FIX ME: The unloading of GRP entry is temporarily disabled
977     //    because ZDC and VZERO are using it in order to initialize
978     //    their reconstructor objects. In the future one has to think
979     //    of propagating AliRunInfo to the reconstructors.
980     //    AliCDBManager::Instance()->UnloadFromCache("GRP/GRP/Data");
981   }
982
983   if (!fGRPData) {
984      AliError("No GRP entry found in OCDB!");
985      return kFALSE;
986   }
987
988   TString lhcState = fGRPData->GetLHCState();
989   if (lhcState==AliGRPObject::GetInvalidString()) {
990     AliError("GRP/GRP/Data entry:  missing value for the LHC state ! Using UNKNOWN");
991     lhcState = "UNKNOWN";
992   }
993
994   TString beamType = fGRPData->GetBeamType();
995   if (beamType==AliGRPObject::GetInvalidString()) {
996     AliError("GRP/GRP/Data entry:  missing value for the beam type ! Using UNKNOWN");
997     beamType = "UNKNOWN";
998   }
999
1000   Float_t beamEnergy = fGRPData->GetBeamEnergy();
1001   if (beamEnergy==AliGRPObject::GetInvalidFloat()) {
1002     AliError("GRP/GRP/Data entry:  missing value for the beam energy ! Using 0");
1003     beamEnergy = 0;
1004   }
1005
1006   TString runType = fGRPData->GetRunType();
1007   if (runType==AliGRPObject::GetInvalidString()) {
1008     AliError("GRP/GRP/Data entry:  missing value for the run type ! Using UNKNOWN");
1009     runType = "UNKNOWN";
1010   }
1011
1012   Int_t activeDetectors = fGRPData->GetDetectorMask();
1013   if (activeDetectors==AliGRPObject::GetInvalidUInt()) {
1014     AliError("GRP/GRP/Data entry:  missing value for the detector mask ! Using 1074790399");
1015     activeDetectors = 1074790399;
1016   }
1017
1018   fRunInfo = new AliRunInfo(lhcState, beamType, beamEnergy, runType, activeDetectors);
1019   fRunInfo->Dump();
1020
1021
1022   // Process the list of active detectors
1023   if (activeDetectors) {
1024     UInt_t detMask = activeDetectors;
1025     fRunLocalReconstruction = MatchDetectorList(fRunLocalReconstruction,detMask);
1026     fRunTracking = MatchDetectorList(fRunTracking,detMask);
1027     fFillESD = MatchDetectorList(fFillESD,detMask);
1028     fQADetectors = MatchDetectorList(fQADetectors,detMask);
1029     fLoadCDB.Form("%s %s %s %s",
1030                   fRunLocalReconstruction.Data(),
1031                   fRunTracking.Data(),
1032                   fFillESD.Data(),
1033                   fQADetectors.Data());
1034     fLoadCDB = MatchDetectorList(fLoadCDB,detMask);
1035     if (!((detMask >> AliDAQ::DetectorID("ITSSPD")) & 0x1) &&
1036         !((detMask >> AliDAQ::DetectorID("ITSSDD")) & 0x1) &&
1037         !((detMask >> AliDAQ::DetectorID("ITSSSD")) & 0x1) ) {
1038       // switch off the vertexer
1039       AliInfo("SPD,SDD,SSD is not in the list of active detectors. Vertexer and Trackleter are switched off.");
1040       fRunVertexFinder = kFALSE;
1041       fRunMultFinder = kFALSE;
1042     }
1043     if (!((detMask >> AliDAQ::DetectorID("TRG")) & 0x1)) {
1044       // switch off the reading of CTP raw-data payload
1045       if (fFillTriggerESD) {
1046         AliInfo("CTP is not in the list of active detectors. CTP data reading switched off.");
1047         fFillTriggerESD = kFALSE;
1048       }
1049     }
1050   }
1051
1052   AliInfo("===================================================================================");
1053   AliInfo(Form("Running local reconstruction for detectors: %s",fRunLocalReconstruction.Data()));
1054   AliInfo(Form("Running tracking for detectors: %s",fRunTracking.Data()));
1055   AliInfo(Form("Filling ESD for detectors: %s",fFillESD.Data()));
1056   AliInfo(Form("Quality assurance is active for detectors: %s",fQADetectors.Data()));
1057   AliInfo(Form("CDB and reconstruction parameters are loaded for detectors: %s",fLoadCDB.Data()));
1058   AliInfo("===================================================================================");
1059
1060   //*** Dealing with the magnetic field map
1061   if ( TGeoGlobalMagField::Instance()->IsLocked() ) {
1062     if (TGeoGlobalMagField::Instance()->GetField()->TestBit(AliMagF::kOverrideGRP)) {
1063       AliInfo("ExpertMode!!! GRP information will be ignored !");
1064       AliInfo("ExpertMode!!! Running with the externally locked B field !");
1065     }
1066     else {
1067       AliInfo("Destroying existing B field instance!");
1068       delete TGeoGlobalMagField::Instance();
1069     }    
1070   }
1071   if ( !TGeoGlobalMagField::Instance()->IsLocked() ) {
1072     // Construct the field map out of the information retrieved from GRP.
1073     Bool_t ok = kTRUE;
1074     // L3
1075     Float_t l3Current = fGRPData->GetL3Current((AliGRPObject::Stats)0);
1076     if (l3Current == AliGRPObject::GetInvalidFloat()) {
1077       AliError("GRP/GRP/Data entry:  missing value for the L3 current !");
1078       ok = kFALSE;
1079     }
1080     
1081     Char_t l3Polarity = fGRPData->GetL3Polarity();
1082     if (l3Polarity == AliGRPObject::GetInvalidChar()) {
1083       AliError("GRP/GRP/Data entry:  missing value for the L3 polarity !");
1084       ok = kFALSE;
1085     }
1086
1087     // Dipole
1088     Float_t diCurrent = fGRPData->GetDipoleCurrent((AliGRPObject::Stats)0);
1089     if (diCurrent == AliGRPObject::GetInvalidFloat()) {
1090       AliError("GRP/GRP/Data entry:  missing value for the dipole current !");
1091       ok = kFALSE;
1092     }
1093
1094     Char_t diPolarity = fGRPData->GetDipolePolarity();
1095     if (diPolarity == AliGRPObject::GetInvalidChar()) {
1096       AliError("GRP/GRP/Data entry:  missing value for the dipole polarity !");
1097       ok = kFALSE;
1098     }
1099
1100     // read special bits for the polarity convention and map type
1101     Int_t  polConvention = fGRPData->IsPolarityConventionLHC() ? AliMagF::kConvLHC : AliMagF::kConvDCS2008;
1102     Bool_t uniformB = fGRPData->IsUniformBMap();
1103
1104     if (ok) { 
1105       AliMagF* fld = AliMagF::CreateFieldMap(TMath::Abs(l3Current) * (l3Polarity ? -1:1), 
1106                                              TMath::Abs(diCurrent) * (diPolarity ? -1:1), 
1107                                              polConvention,uniformB,beamEnergy, beamType.Data());
1108       if (fld) {
1109         TGeoGlobalMagField::Instance()->SetField( fld );
1110         TGeoGlobalMagField::Instance()->Lock();
1111         AliInfo("Running with the B field constructed out of GRP !");
1112       }
1113       else AliFatal("Failed to create a B field map !");
1114     }
1115     else AliFatal("B field is neither set nor constructed from GRP ! Exitig...");
1116   }
1117   
1118   //*** Get the diamond profiles from OCDB
1119   entry = AliCDBManager::Instance()->Get("GRP/Calib/MeanVertexSPD");
1120   if (entry) {
1121     fDiamondProfileSPD = dynamic_cast<AliESDVertex*> (entry->GetObject());  
1122   } else {
1123      AliError("No SPD diamond profile found in OCDB!");
1124   }
1125
1126   entry = AliCDBManager::Instance()->Get("GRP/Calib/MeanVertex");
1127   if (entry) {
1128     fDiamondProfile = dynamic_cast<AliESDVertex*> (entry->GetObject());  
1129   } else {
1130      AliError("No diamond profile found in OCDB!");
1131   }
1132
1133   entry = AliCDBManager::Instance()->Get("GRP/Calib/MeanVertexTPC");
1134   if (entry) {
1135     fDiamondProfileTPC = dynamic_cast<AliESDVertex*> (entry->GetObject());  
1136   } else {
1137      AliError("No TPC diamond profile found in OCDB!");
1138   }
1139
1140   entry = AliCDBManager::Instance()->Get("GRP/Calib/CosmicTriggers");
1141   if (entry) {
1142     fListOfCosmicTriggers = dynamic_cast<THashTable*>(entry->GetObject());
1143     entry->SetOwner(0);
1144     AliCDBManager::Instance()->UnloadFromCache("GRP/Calib/CosmicTriggers");
1145   }
1146
1147   if (!fListOfCosmicTriggers) {
1148     AliWarning("Can not get list of cosmic triggers from OCDB! Cosmic event specie will be effectively disabled!");
1149   }
1150
1151   return kTRUE;
1152
1153
1154 //_____________________________________________________________________________
1155 Bool_t AliReconstruction::LoadCDB()
1156 {
1157   // Load CDB entries for all active detectors.
1158   // By default we load all the entries in <det>/Calib
1159   // folder.
1160
1161   AliCodeTimerAuto("",0);
1162
1163   AliCDBManager::Instance()->Get("GRP/CTP/Config");
1164
1165   TString detStr = fLoadCDB;
1166   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
1167     if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
1168     AliCDBManager::Instance()->GetAll(Form("%s/Calib/*",fgkDetectorName[iDet]));
1169   }
1170
1171   // Temporary fix - one has to define the correct policy in order
1172   // to load the trigger OCDB entries only for the detectors that
1173   // in the trigger or that are needed in order to put correct
1174   // information in ESD
1175   AliCDBManager::Instance()->GetAll("TRIGGER/*/*");
1176
1177   return kTRUE;
1178 }
1179 //_____________________________________________________________________________
1180 Bool_t AliReconstruction::LoadTriggerScalersCDB()
1181 {
1182   // Load CTP scalers from OCDB.
1183   // The scalers are checked for consistency.
1184
1185   AliCodeTimerAuto("",0);
1186
1187   AliCDBEntry* entry = AliCDBManager::Instance()->Get("GRP/CTP/Scalers");
1188
1189   if (entry) { 
1190    
1191        AliInfo("Found an AliTriggerRunScalers in GRP/CTP/Scalers, reading it");
1192        fRunScalers = dynamic_cast<AliTriggerRunScalers*> (entry->GetObject());
1193        entry->SetOwner(0);
1194        if (fRunScalers->CorrectScalersOverflow() == 0) AliInfo("32bit Trigger counters corrected for overflow");
1195
1196   }
1197   return kTRUE;
1198 }
1199 //_____________________________________________________________________________
1200 Bool_t AliReconstruction::LoadCTPTimeParamsCDB()
1201 {
1202   // Load CTP timing information (alignment)
1203   // from OCDB.
1204
1205   AliCDBEntry* entry = AliCDBManager::Instance()->Get("GRP/CTP/CTPtiming");
1206
1207   if (entry) {
1208
1209        AliInfo("Found an AliCTPTimeParams in GRP/CTP/CTPtiming, reading it");
1210        fCTPTimeParams = dynamic_cast<AliCTPTimeParams*> (entry->GetObject());
1211        entry->SetOwner(0);
1212        return kTRUE;
1213   }
1214   
1215   return kFALSE; 
1216 }
1217
1218 //_____________________________________________________________________________
1219 Bool_t AliReconstruction::ReadIntensityInfoCDB()
1220 {
1221   // Load LHC DIP data
1222   AliCDBEntry* entry = AliCDBManager::Instance()->Get("GRP/GRP/LHCData");
1223
1224   if (entry) { 
1225     AliInfo("Found an AliLHCData in GRP/GRP/LHCData, reading it");
1226     AliLHCData* dipData = dynamic_cast<AliLHCData*> (entry->GetObject());
1227     for (int ib=2;ib--;) {
1228       double intI,intNI;
1229       if (dipData->GetMeanIntensity(ib,intI,intNI)>=0) {
1230         fBeamInt[ib][0] = intI;
1231         fBeamInt[ib][1] = intNI;        
1232       }
1233     }
1234     return kTRUE;
1235   }
1236   return kFALSE;
1237 }
1238
1239
1240 //_____________________________________________________________________________
1241 Bool_t AliReconstruction::Run(const char* input)
1242 {
1243   // Run Run Run
1244   AliCodeTimerAuto("",0);
1245
1246   InitRun(input);
1247   if (GetAbort() != TSelector::kContinue) return kFALSE;
1248
1249   TChain *chain = NULL;
1250   if (fRawReader && (chain = fRawReader->GetChain())) {
1251     Long64_t nEntries = (fLastEvent < 0) ? (TChain::kBigNumber) : (fLastEvent - fFirstEvent + 1);
1252     // Proof mode
1253     if (gProof) {
1254       // Temporary fix for long raw-data runs (until socket timeout handling in PROOF is revised)
1255       gProof->Exec("gEnv->SetValue(\"Proof.SocketActivityTimeout\",-1)", kTRUE);
1256
1257       if (gGrid)
1258         gProof->Exec("TGrid::Connect(\"alien://\")",kTRUE);
1259
1260       TMessage::EnableSchemaEvolutionForAll(kTRUE);
1261       gProof->Exec("TMessage::EnableSchemaEvolutionForAll(kTRUE)",kTRUE);
1262
1263       gProof->AddInput(this);
1264
1265       if (!ParseOutput()) return kFALSE;
1266
1267       gProof->SetParameter("PROOF_MaxSlavesPerNode", 9999);
1268       chain->SetProof();
1269       chain->Process("AliReconstruction","",nEntries,fFirstEvent);
1270     }
1271     else {
1272       chain->Process(this,"",nEntries,fFirstEvent);
1273     }
1274   }
1275   else {
1276     Begin(NULL);
1277     if (GetAbort() != TSelector::kContinue) return kFALSE;
1278     SlaveBegin(NULL);
1279     if (GetAbort() != TSelector::kContinue) return kFALSE;
1280     //******* The loop over events
1281     AliInfo("Starting looping over events");
1282     Int_t iEvent = 0;
1283     while ((iEvent < fRunLoader->GetNumberOfEvents()) ||
1284            (fRawReader && fRawReader->NextEvent())) {
1285       if (!ProcessEvent(iEvent)) {
1286         Abort("ProcessEvent",TSelector::kAbortFile);
1287         return kFALSE;
1288       }
1289       iEvent++;
1290     }
1291     SlaveTerminate();
1292     if (GetAbort() != TSelector::kContinue) return kFALSE;
1293     Terminate();
1294     if (GetAbort() != TSelector::kContinue) return kFALSE;
1295   }
1296
1297   return kTRUE;
1298 }
1299
1300 //_____________________________________________________________________________
1301 void AliReconstruction::InitRawReader(const char* input)
1302 {
1303   // Init raw-reader and
1304   // set the input in case of raw data
1305
1306   AliCodeTimerAuto("",0);
1307
1308   if (input) fRawInput = input;
1309   fRawReader = AliRawReader::Create(fRawInput.Data());
1310   if (!fRawReader) {
1311     if (fRawInput.IsNull()) {
1312       AliInfo("Reconstruction will run over digits");
1313     }
1314     else {
1315       AliFatal("Can not create raw-data reader ! Exiting..."); 
1316     }
1317   }
1318
1319   if (!fEquipIdMap.IsNull() && fRawReader)
1320     fRawReader->LoadEquipmentIdsMap(fEquipIdMap);
1321
1322   if (!fUseHLTData.IsNull()) {
1323     // create the RawReaderHLT which performs redirection of HLT input data for
1324     // the specified detectors
1325     AliRawReader* pRawReader=AliRawHLTManager::CreateRawReaderHLT(fRawReader, fUseHLTData.Data());
1326     if (pRawReader) {
1327       fParentRawReader=fRawReader;
1328       fRawReader=pRawReader;
1329     } else {
1330       AliError(Form("can not create Raw Reader for HLT input %s", fUseHLTData.Data()));
1331     }
1332   }
1333   AliSysInfo::AddStamp("CreateRawReader");
1334 }
1335
1336 //_____________________________________________________________________________
1337 void AliReconstruction::InitRun(const char* input)
1338 {
1339   // Initialization of raw-reader,
1340   // run number, CDB etc.
1341   AliCodeTimerAuto("",0);
1342   AliSysInfo::AddStamp("Start");
1343
1344   // Initialize raw-reader if any
1345   InitRawReader(input);
1346
1347   // Initialize the CDB storage
1348   InitCDB();
1349
1350   // Set run number in CDBManager (if it is not already set by the user)
1351   if (!SetRunNumberFromData()) {
1352     Abort("SetRunNumberFromData", TSelector::kAbortProcess);
1353     return;
1354   }
1355
1356   // Set CDB lock: from now on it is forbidden to reset the run number
1357   // or the default storage or to activate any further storage!
1358   SetCDBLock();
1359   
1360 }
1361
1362 //_____________________________________________________________________________
1363 void AliReconstruction::Begin(TTree *)
1364 {
1365   // Initialize AlReconstruction before
1366   // going into the event loop
1367   // Should follow the TSelector convention
1368   // i.e. initialize only the object on the client side
1369   AliCodeTimerAuto("",0);
1370
1371   AliReconstruction *reco = NULL;
1372   if (fInput) {
1373     if ((reco = (AliReconstruction*)fInput->FindObject("AliReconstruction"))) {
1374       *this = *reco;
1375     }
1376     AliSysInfo::AddStamp("ReadInputInBegin");
1377   }
1378
1379   // Import ideal TGeo geometry and apply misalignment
1380   if (!gGeoManager) {
1381     TString geom(gSystem->DirName(fGAliceFileName));
1382     geom += "/geometry.root";
1383     AliGeomManager::LoadGeometry(geom.Data());
1384     if (!gGeoManager) {
1385       Abort("LoadGeometry", TSelector::kAbortProcess);
1386       return;
1387     }
1388     AliSysInfo::AddStamp("LoadGeom");
1389     TString detsToCheck=fRunLocalReconstruction;
1390     if(!AliGeomManager::CheckSymNamesLUT(detsToCheck.Data())) {
1391       Abort("CheckSymNamesLUT", TSelector::kAbortProcess);
1392       return;
1393     }
1394     AliSysInfo::AddStamp("CheckGeom");
1395   }
1396
1397   if (!MisalignGeometry(fLoadAlignData)) {
1398     Abort("MisalignGeometry", TSelector::kAbortProcess);
1399     return;
1400   }
1401   AliCDBManager::Instance()->UnloadFromCache("GRP/Geometry/Data");
1402   AliSysInfo::AddStamp("MisalignGeom");
1403
1404   if (!InitGRP()) {
1405     Abort("InitGRP", TSelector::kAbortProcess);
1406     return;
1407   }
1408   AliSysInfo::AddStamp("InitGRP");
1409
1410   if (!LoadCDB()) {
1411     Abort("LoadCDB", TSelector::kAbortProcess);
1412     return;
1413   }
1414   AliSysInfo::AddStamp("LoadCDB");
1415
1416   if (!LoadTriggerScalersCDB()) {
1417     Abort("LoadTriggerScalersCDB", TSelector::kAbortProcess);
1418     return;
1419   }
1420   AliSysInfo::AddStamp("LoadTriggerScalersCDB");
1421
1422   if (!LoadCTPTimeParamsCDB()) {
1423     Abort("LoadCTPTimeParamsCDB", TSelector::kAbortProcess);
1424     return;
1425   }
1426   AliSysInfo::AddStamp("LoadCTPTimeParamsCDB");
1427
1428   if (!ReadIntensityInfoCDB()) {
1429     Abort("ReadIntensityInfoCDB", TSelector::kAbortProcess);
1430     return;
1431   }
1432   AliSysInfo::AddStamp("ReadIntensityInfoCDB");
1433
1434   // Read the reconstruction parameters from OCDB
1435   if (!InitRecoParams()) {
1436     AliWarning("Not all detectors have correct RecoParam objects initialized");
1437   }
1438   AliSysInfo::AddStamp("InitRecoParams");
1439
1440   if (fInput && gProof) {
1441     if (reco) *reco = *this;
1442
1443     gGeoManager->SetName("Geometry");
1444     gProof->AddInputData(gGeoManager,kTRUE);
1445     gGeoManager = NULL;
1446     gProof->AddInputData(const_cast<TMap*>(AliCDBManager::Instance()->GetEntryCache()),kTRUE);
1447     fInput->Add(new TParameter<Int_t>("RunNumber",AliCDBManager::Instance()->GetRun()));
1448     AliMagF *magFieldMap = (AliMagF*)TGeoGlobalMagField::Instance()->GetField();
1449     magFieldMap->SetName("MagneticFieldMap");
1450     gProof->AddInputData(magFieldMap,kTRUE);
1451   }
1452
1453 }
1454
1455 //_____________________________________________________________________________
1456 void AliReconstruction::SlaveBegin(TTree*)
1457 {
1458   // Initialization related to run-loader,
1459   // vertexer, trackers, recontructors
1460   // In proof mode it is executed on the slave
1461   AliCodeTimerAuto("",0);
1462
1463   TProofOutputFile *outProofFile = NULL;
1464   if (fInput) {
1465     if (AliDebugLevel() > 0) fInput->Print();
1466     if (AliDebugLevel() > 10) fInput->Dump();
1467     if (AliReconstruction *reco = (AliReconstruction*)fInput->FindObject("AliReconstruction")) {
1468       *this = *reco;
1469     }
1470     if (TGeoManager *tgeo = (TGeoManager*)fInput->FindObject("Geometry")) {
1471       gGeoManager = tgeo;
1472       AliGeomManager::SetGeometry(tgeo);
1473     }
1474     if (TMap *entryCache = (TMap*)fInput->FindObject("CDBEntryCache")) {
1475       Int_t runNumber = -1;
1476       if (TProof::GetParameter(fInput,"RunNumber",runNumber) == 0) {
1477         AliCDBManager *man = AliCDBManager::Instance(entryCache,runNumber);
1478         man->SetCacheFlag(kTRUE);
1479         man->SetLock(kTRUE);
1480         man->Print();
1481       }
1482     }
1483     if (AliMagF *map = (AliMagF*)fInput->FindObject("MagneticFieldMap")) {
1484       AliMagF *newMap = new AliMagF(*map);
1485       if (!newMap->LoadParameterization()) {
1486         Abort("AliMagF::LoadParameterization", TSelector::kAbortProcess);
1487         return;
1488       }
1489       TGeoGlobalMagField::Instance()->SetField(newMap);
1490       TGeoGlobalMagField::Instance()->Lock();
1491     }
1492     if (TNamed *outputFileName = (TNamed*)fInput->FindObject("PROOF_OUTPUTFILE"))
1493       fProofOutputFileName = outputFileName->GetTitle();
1494     if (TNamed *outputLocation = (TNamed*)fInput->FindObject("PROOF_OUTPUTFILE_LOCATION"))
1495       fProofOutputLocation = outputLocation->GetTitle();
1496     if (fInput->FindObject("PROOF_OUTPUTFILE_DATASET"))
1497       fProofOutputDataset = kTRUE;
1498     if (TNamed *archiveList = (TNamed*)fInput->FindObject("PROOF_OUTPUTFILE_ARCHIVE"))
1499       fProofOutputArchive = archiveList->GetTitle();
1500     if (!fProofOutputFileName.IsNull() &&
1501         !fProofOutputLocation.IsNull() &&
1502         fProofOutputArchive.IsNull()) {
1503       if (!fProofOutputDataset) {
1504         outProofFile = new TProofOutputFile(fProofOutputFileName.Data(),"M");
1505         outProofFile->SetOutputFileName(Form("%s%s",fProofOutputLocation.Data(),fProofOutputFileName.Data()));
1506       }
1507       else {
1508         outProofFile = new TProofOutputFile(fProofOutputFileName.Data(),"DROV",fProofOutputLocation.Data());
1509       }
1510       if (AliDebugLevel() > 0) outProofFile->Dump();
1511       fOutput->Add(outProofFile);
1512     }
1513     AliSysInfo::AddStamp("ReadInputInSlaveBegin");
1514   }
1515
1516   // get the run loader
1517   if (!InitRunLoader()) {
1518     Abort("InitRunLoader", TSelector::kAbortProcess);
1519     return;
1520   }
1521   AliSysInfo::AddStamp("LoadLoader");
1522  
1523   ftVertexer = new AliVertexerTracks(AliTracker::GetBz());
1524
1525   // get trackers
1526   if (!fRunTracking.IsNull() && !CreateTrackers(fRunTracking)) {
1527     Abort("CreateTrackers", TSelector::kAbortProcess);
1528     return;
1529   }      
1530   AliSysInfo::AddStamp("CreateTrackers");
1531
1532   // create the ESD output file and tree
1533   if (!outProofFile) {
1534     ffile = TFile::Open("AliESDs.root", "RECREATE");
1535     ffile->SetCompressionLevel(2);
1536     if (!ffile->IsOpen()) {
1537       Abort("OpenESDFile", TSelector::kAbortProcess);
1538       return;
1539     }
1540   }
1541   else {
1542     AliInfo(Form("Opening output PROOF file: %s/%s",
1543                  outProofFile->GetDir(), outProofFile->GetFileName()));
1544     if (!(ffile = outProofFile->OpenFile("RECREATE"))) {
1545       Abort(Form("Problems opening output PROOF file: %s/%s",
1546                  outProofFile->GetDir(), outProofFile->GetFileName()),
1547             TSelector::kAbortProcess);
1548       return;
1549     }
1550   }
1551
1552   ftree = new TTree("esdTree", "Tree with ESD objects");
1553   fesd = new AliESDEvent();
1554   fesd->CreateStdContent();
1555   // add a so far non-std object to the ESD, this will
1556   // become part of the std content
1557   fesd->AddObject(new AliESDHLTDecision);
1558
1559   fesd->WriteToTree(ftree);
1560   if (fWriteESDfriend) {
1561     ffileF = TFile::Open("AliESDfriends.root", "RECREATE");
1562     ftreeF = new TTree("esdFriendTree", "Tree with ESD Friend objects");
1563     fesdf  = new AliESDfriend();
1564     ftreeF->Branch("ESDfriend.","AliESDfriend", &fesdf);
1565     fesd->AddObject(fesdf);
1566     ffile->cd();
1567   }
1568   ftree->GetUserInfo()->Add(fesd);
1569
1570   fhlttree = new TTree("HLTesdTree", "Tree with HLT ESD objects");
1571   fhltesd = new AliESDEvent();
1572   fhltesd->CreateStdContent();
1573   // read the ESD template from CDB
1574   // HLT is allowed to put non-std content to its ESD, the non-std
1575   // objects need to be created before invocation of WriteToTree in
1576   // order to create all branches. Initialization is done from an
1577   // ESD layout template in CDB
1578   AliCDBManager* man = AliCDBManager::Instance();
1579   AliCDBPath hltESDConfigPath("HLT/ConfigHLT/esdLayout");
1580   AliCDBEntry* hltESDConfig=NULL;
1581   if (man->GetId(hltESDConfigPath)!=NULL &&
1582       (hltESDConfig=man->Get(hltESDConfigPath))!=NULL) {
1583     AliESDEvent* pESDLayout=dynamic_cast<AliESDEvent*>(hltESDConfig->GetObject());
1584     if (pESDLayout) {
1585       // init all internal variables from the list of objects
1586       pESDLayout->GetStdContent();
1587
1588       // copy content and create non-std objects
1589       *fhltesd=*pESDLayout;
1590       fhltesd->Reset();
1591     } else {
1592       AliError(Form("error setting hltEsd layout from %s: invalid object type",
1593                     hltESDConfigPath.GetPath().Data()));
1594     }
1595   }
1596
1597   fhltesd->WriteToTree(fhlttree);
1598   fhlttree->GetUserInfo()->Add(fhltesd);
1599
1600   ProcInfo_t procInfo;
1601   gSystem->GetProcInfo(&procInfo);
1602   AliInfo(Form("Current memory usage %d %d", procInfo.fMemResident, procInfo.fMemVirtual));
1603   
1604   //QA
1605   //Initialize the QA and start of cycle 
1606   if (fRunQA || fRunGlobalQA) 
1607     InitQA() ; 
1608
1609   //Initialize the Plane Efficiency framework
1610   if (fRunPlaneEff && !InitPlaneEff()) {
1611     Abort("InitPlaneEff", TSelector::kAbortProcess);
1612     return;
1613   }
1614
1615   if (strcmp(gProgName,"alieve") == 0)
1616     fRunAliEVE = InitAliEVE();
1617
1618   return;
1619 }
1620
1621 //_____________________________________________________________________________
1622 Bool_t AliReconstruction::Process(Long64_t entry)
1623 {
1624   // run the reconstruction over a single entry
1625   // from the chain with raw data
1626   AliCodeTimerAuto("",0);
1627
1628   TTree *currTree = fChain->GetTree();
1629   AliRawVEvent *event = NULL;
1630   currTree->SetBranchAddress("rawevent",&event);
1631   currTree->GetEntry(entry);
1632   fRawReader = new AliRawReaderRoot(event);
1633   fStatus = ProcessEvent(fRunLoader->GetNumberOfEvents());  
1634   delete fRawReader;
1635   fRawReader = NULL;
1636   delete event;
1637
1638   return fStatus;
1639 }
1640
1641 //_____________________________________________________________________________
1642 void AliReconstruction::Init(TTree *tree)
1643 {
1644   // Implementation of TSelector::Init()
1645   // method
1646   if (tree == 0) {
1647     AliError("The input tree is not found!");
1648     return;
1649   }
1650   fChain = tree;
1651 }
1652
1653 //_____________________________________________________________________________
1654 Bool_t AliReconstruction::ProcessEvent(Int_t iEvent)
1655 {
1656   // run the reconstruction over a single event
1657   // The event loop is steered in Run method
1658
1659
1660   static Long_t oldMres=0;
1661   static Long_t oldMvir=0;
1662   static Float_t oldCPU=0;
1663   static Long_t aveDMres=0;
1664   static Long_t aveDMvir=0;
1665   static Float_t aveDCPU=0;
1666
1667   AliCodeTimerAuto("",0);
1668
1669   AliESDpid pid;
1670
1671   if (iEvent >= fRunLoader->GetNumberOfEvents()) {
1672     fRunLoader->SetEventNumber(iEvent);
1673     fRunLoader->GetHeader()->Reset(fRawReader->GetRunNumber(), 
1674                                    iEvent, iEvent);
1675     fRunLoader->TreeE()->Fill();
1676     if (fRawReader && fRawReader->UseAutoSaveESD())
1677       fRunLoader->TreeE()->AutoSave("SaveSelf");
1678   }
1679
1680   if ((iEvent < fFirstEvent) || ((fLastEvent >= 0) && (iEvent > fLastEvent))) {
1681     return kTRUE;
1682   }
1683
1684
1685   fRunLoader->GetEvent(iEvent);
1686
1687   // Fill Event-info object
1688   GetEventInfo();
1689   fRecoParam.SetEventSpecie(fRunInfo,fEventInfo,fListOfCosmicTriggers);
1690   
1691   ProcInfo_t procInfo;
1692   if(iEvent==fFirstEvent) {
1693     gSystem->GetProcInfo(&procInfo);
1694     oldMres=procInfo.fMemResident;
1695     oldMvir=procInfo.fMemVirtual;
1696     oldCPU=procInfo.fCpuUser+procInfo.fCpuSys;
1697   }
1698   AliInfo(Form("================================= Processing event %d of type %-10s ==================================", iEvent,fRecoParam.PrintEventSpecie()));
1699
1700   // Set the reco-params
1701   {
1702     TString detStr = fLoadCDB;
1703     for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
1704       if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
1705       AliReconstructor *reconstructor = GetReconstructor(iDet);
1706       if (reconstructor && fRecoParam.GetDetRecoParamArray(iDet)) {
1707         const AliDetectorRecoParam *par = fRecoParam.GetDetRecoParam(iDet);
1708         reconstructor->SetRecoParam(par);
1709         reconstructor->GetPidSettings(&pid);
1710         reconstructor->SetEventInfo(&fEventInfo);
1711         if (fRunQA) {
1712           AliQAManager::QAManager()->SetRecoParam(iDet, par) ; 
1713           if (par) AliQAManager::QAManager()->SetEventSpecie(AliRecoParam::Convert(par->GetEventSpecie())) ;
1714         }
1715       }
1716     }
1717     if (fRunQA) {
1718       const AliDetectorRecoParam *grppar = fRecoParam.GetDetRecoParam(kNDetectors);
1719       AliQAManager::QAManager()->SetRecoParam(AliQAv1::kGLOBAL, grppar) ; 
1720       AliQAManager::QAManager()->SetEventSpecie(AliRecoParam::Convert(grppar->GetEventSpecie())) ;
1721     }
1722   }
1723
1724     // QA on single raw 
1725   if (fRunQA && IsInTasks(AliQAv1::kRAWS)) {
1726     AliQAManager::QAManager()->SetEventSpecie(fRecoParam.GetEventSpecie()) ;
1727     AliQAManager::QAManager()->RunOneEvent(fRawReader) ;  
1728   }
1729     // local single event reconstruction
1730     if (!fRunLocalReconstruction.IsNull()) {
1731       TString detectors=fRunLocalReconstruction;
1732       // run HLT event reconstruction first
1733       // ;-( IsSelected changes the string
1734       if (IsSelected("HLT", detectors) &&
1735           !RunLocalEventReconstruction("HLT")) {
1736         if (fStopOnError) {CleanUp(); return kFALSE;}
1737       }
1738       detectors=fRunLocalReconstruction;
1739       detectors.ReplaceAll("HLT", "");
1740       if (!RunLocalEventReconstruction(detectors)) {
1741         if (fStopOnError) {
1742           CleanUp(); 
1743           return kFALSE;
1744         }
1745       }
1746     }
1747
1748   
1749     // fill Event header information from the RawEventHeader
1750     if (fRawReader){FillRawEventHeaderESD(fesd);}
1751     if (fRawReader){FillRawEventHeaderESD(fhltesd);}
1752
1753     fesd->SetRunNumber(fRunLoader->GetHeader()->GetRun());
1754     fhltesd->SetRunNumber(fRunLoader->GetHeader()->GetRun());
1755     
1756     ((AliESDRun*)fesd->GetESDRun())->SetDetectorsInDAQ(fRunInfo->GetDetectorMask());
1757     ((AliESDRun*)fhltesd->GetESDRun())->SetDetectorsInDAQ(fRunInfo->GetDetectorMask());
1758     ((AliESDRun*)fesd->GetESDRun())->SetDetectorsInReco(AliDAQ::DetectorPatternOffline(fFillESD.Data()));
1759     ((AliESDRun*)fhltesd->GetESDRun())->SetDetectorsInReco(AliDAQ::DetectorPatternOffline(fFillESD.Data()));
1760
1761     fesd->SetEventNumberInFile(fRunLoader->GetHeader()->GetEventNrInRun());
1762     fhltesd->SetEventNumberInFile(fRunLoader->GetHeader()->GetEventNrInRun());
1763
1764     fesd->SetEventSpecie(fRecoParam.GetEventSpecie());
1765     fhltesd->SetEventSpecie(fRecoParam.GetEventSpecie());
1766     
1767     // Set magnetic field from the tracker
1768     fesd->SetMagneticField(AliTracker::GetBz());
1769     fhltesd->SetMagneticField(AliTracker::GetBz());
1770     //
1771     AliESDRun *esdRun,*esdRunH;
1772     esdRun  = (AliESDRun*)fesd->GetESDRun();
1773     esdRunH = (AliESDRun*)fhltesd->GetESDRun();
1774     esdRun->SetBeamEnergyIsSqrtSHalfGeV();
1775     esdRunH->SetBeamEnergyIsSqrtSHalfGeV();
1776     //
1777     for (int ib=2;ib--;) for (int it=2;it--;) {
1778         esdRun->SetMeanIntensity(ib,it, fBeamInt[ib][it]); 
1779         esdRunH->SetMeanIntensity(ib,it, fBeamInt[ib][it]); 
1780       }
1781     //
1782     AliMagF* fld = (AliMagF*)TGeoGlobalMagField::Instance()->GetField();
1783     if (fld) { // set info needed for field initialization
1784       fesd->SetCurrentL3(fld->GetCurrentSol());
1785       fesd->SetCurrentDip(fld->GetCurrentDip());
1786       fesd->SetBeamEnergy(fld->GetBeamEnergy());
1787       fesd->SetBeamType(fld->GetBeamTypeText());
1788       fesd->SetUniformBMap(fld->IsUniform());
1789       fesd->SetBInfoStored();
1790       //
1791       fhltesd->SetCurrentL3(fld->GetCurrentSol());
1792       fhltesd->SetCurrentDip(fld->GetCurrentDip());
1793       fhltesd->SetBeamEnergy(fld->GetBeamEnergy());
1794       fhltesd->SetBeamType(fld->GetBeamTypeText());
1795       fhltesd->SetUniformBMap(fld->IsUniform());
1796       fhltesd->SetBInfoStored();
1797     }
1798     //
1799     // Set most probable pt, for B=0 tracking
1800     // Get the global reco-params. They are atposition 16 inside the array of detectors in fRecoParam
1801     const AliGRPRecoParam *grpRecoParam = dynamic_cast<const AliGRPRecoParam*>(fRecoParam.GetDetRecoParam(kNDetectors));
1802     if (grpRecoParam) AliExternalTrackParam::SetMostProbablePt(grpRecoParam->GetMostProbablePt());
1803     
1804     // Fill raw-data error log into the ESD
1805     if (fRawReader) FillRawDataErrorLog(iEvent,fesd);
1806
1807     // vertex finder
1808     if (fRunVertexFinder) {
1809       if (!RunVertexFinder(fesd)) {
1810         if (fStopOnError) {CleanUp(); return kFALSE;}
1811       }
1812     }
1813
1814     // For Plane Efficiency: run the SPD trackleter
1815     if (fRunPlaneEff && fSPDTrackleter) {
1816       if (!RunSPDTrackleting(fesd)) {
1817         if (fStopOnError) {CleanUp(); return kFALSE;}
1818       }
1819     }
1820
1821     // Muon tracking
1822     if (!fRunTracking.IsNull()) {
1823       if (fRunMuonTracking) {
1824         if (!RunMuonTracking(fesd)) {
1825           if (fStopOnError) {CleanUp(); return kFALSE;}
1826         }
1827       }
1828     }
1829
1830     // barrel tracking
1831     if (!fRunTracking.IsNull()) {
1832       if (!RunTracking(fesd,pid)) {
1833         if (fStopOnError) {CleanUp(); return kFALSE;}
1834       }
1835     }
1836
1837     // fill ESD
1838     if (!fFillESD.IsNull()) {
1839       TString detectors=fFillESD;
1840       // run HLT first and on hltesd
1841       // ;-( IsSelected changes the string
1842       if (IsSelected("HLT", detectors) &&
1843           !FillESD(fhltesd, "HLT")) {
1844         if (fStopOnError) {CleanUp(); return kFALSE;}
1845       }
1846       detectors=fFillESD;
1847       // Temporary fix to avoid problems with HLT that overwrites the offline ESDs
1848       if (detectors.Contains("ALL")) {
1849         detectors="";
1850         for (Int_t idet=0; idet<kNDetectors; ++idet){
1851           detectors += fgkDetectorName[idet];
1852           detectors += " ";
1853         }
1854       }
1855       detectors.ReplaceAll("HLT", "");
1856       if (!FillESD(fesd, detectors)) {
1857         if (fStopOnError) {CleanUp(); return kFALSE;}
1858       }
1859     }
1860  
1861     // combined PID
1862     pid.MakePID(fesd);
1863
1864     if (fFillTriggerESD) {
1865       if (!FillTriggerESD(fesd)) {
1866         if (fStopOnError) {CleanUp(); return kFALSE;}
1867       }
1868     }
1869     // Always fill scalers
1870     if (!FillTriggerScalers(fesd)) {
1871        if (fStopOnError) {CleanUp(); return kFALSE;}
1872     }
1873     
1874
1875     ffile->cd();
1876
1877     //
1878     // Propagate track to the beam pipe  (if not already done by ITS)
1879     //
1880     const Int_t ntracks = fesd->GetNumberOfTracks();
1881     const Double_t kRadius  = 2.8; //something less than the beam pipe radius
1882
1883     TObjArray trkArray;
1884     UShort_t *selectedIdx=new UShort_t[ntracks];
1885
1886     for (Int_t itrack=0; itrack<ntracks; itrack++){
1887       const Double_t kMaxStep = 1;   //max step over the material
1888       Bool_t ok;
1889
1890       AliESDtrack *track = fesd->GetTrack(itrack);
1891       if (!track) continue;
1892
1893       AliExternalTrackParam *tpcTrack =
1894            (AliExternalTrackParam *)track->GetTPCInnerParam();
1895       ok = kFALSE;
1896       if (tpcTrack)
1897         ok = AliTracker::
1898           PropagateTrackToBxByBz(tpcTrack,kRadius,track->GetMass(),kMaxStep,kFALSE);
1899
1900       if (ok) {
1901         Int_t n=trkArray.GetEntriesFast();
1902         selectedIdx[n]=track->GetID();
1903         trkArray.AddLast(tpcTrack);
1904       }
1905
1906       //Tracks refitted by ITS should already be at the SPD vertex
1907       if (track->IsOn(AliESDtrack::kITSrefit)) continue;
1908
1909       AliTracker::
1910          PropagateTrackToBxByBz(track,kRadius,track->GetMass(),kMaxStep,kFALSE);
1911       Double_t x[3]; track->GetXYZ(x);
1912       Double_t b[3]; AliTracker::GetBxByBz(x,b);
1913       track->RelateToVertexBxByBz(fesd->GetPrimaryVertexSPD(), b, kVeryBig);
1914
1915     }
1916
1917     //
1918     // Improve the reconstructed primary vertex position using the tracks
1919     //
1920     Bool_t runVertexFinderTracks = fRunVertexFinderTracks;
1921     if(fesd->GetPrimaryVertexSPD()) {
1922       TString vtitle = fesd->GetPrimaryVertexSPD()->GetTitle();
1923       if(vtitle.Contains("cosmics")) {
1924         runVertexFinderTracks=kFALSE;
1925       }
1926     }
1927
1928     if (runVertexFinderTracks) {
1929        // TPC + ITS primary vertex
1930        ftVertexer->SetITSMode();
1931        ftVertexer->SetConstraintOff();
1932        // get cuts for vertexer from AliGRPRecoParam
1933        Bool_t constrSPD=kFALSE;
1934        if (grpRecoParam) {
1935          Int_t nCutsVertexer = grpRecoParam->GetVertexerTracksNCuts();
1936          Double_t *cutsVertexer = new Double_t[nCutsVertexer];
1937          grpRecoParam->GetVertexerTracksCutsITS(cutsVertexer);
1938          ftVertexer->SetCuts(cutsVertexer);
1939          delete [] cutsVertexer; cutsVertexer = NULL; 
1940          if(grpRecoParam->GetVertexerTracksConstraintITS()) { 
1941            if(fDiamondProfile && fDiamondProfile->GetXRes()<kRadius){
1942              ftVertexer->SetVtxStart(fDiamondProfile); // apply constraint only if sigmax is smaller than the beam pipe radius 
1943            }else{
1944              if(fDiamondProfileSPD && fDiamondProfileSPD->GetXRes()<kRadius){
1945                ftVertexer->SetVtxStart(fDiamondProfileSPD);
1946                constrSPD=kTRUE;
1947              }
1948            }
1949          } 
1950        }
1951        AliESDVertex *pvtx=ftVertexer->FindPrimaryVertex(fesd);
1952        if (pvtx) {
1953          if(constrSPD){
1954            TString title=pvtx->GetTitle();
1955            title.Append("SPD");
1956            pvtx->SetTitle(title);
1957          }
1958           if (pvtx->GetStatus()) {
1959              fesd->SetPrimaryVertexTracks(pvtx);
1960              for (Int_t i=0; i<ntracks; i++) {
1961                  AliESDtrack *t = fesd->GetTrack(i);
1962                  Double_t x[3]; t->GetXYZ(x);
1963                  Double_t b[3]; AliTracker::GetBxByBz(x,b);
1964                  t->RelateToVertexBxByBz(pvtx, b, kVeryBig);
1965              } 
1966           }
1967           delete pvtx; pvtx=NULL;
1968        }
1969
1970        // TPC-only primary vertex
1971        ftVertexer->SetTPCMode();
1972        ftVertexer->SetConstraintOff();
1973        // get cuts for vertexer from AliGRPRecoParam
1974        if (grpRecoParam) {
1975          Int_t nCutsVertexer = grpRecoParam->GetVertexerTracksNCuts();
1976          Double_t *cutsVertexer = new Double_t[nCutsVertexer];
1977          grpRecoParam->GetVertexerTracksCutsTPC(cutsVertexer);
1978          ftVertexer->SetCuts(cutsVertexer);
1979          delete [] cutsVertexer; cutsVertexer = NULL; 
1980          if(fDiamondProfileTPC && grpRecoParam->GetVertexerTracksConstraintTPC()) { 
1981            if(fDiamondProfileTPC->GetXRes()<kRadius) ftVertexer->SetVtxStart(fDiamondProfileTPC); // apply constraint only if sigmax is smaller than the beam pipe radius 
1982          } 
1983        }
1984        pvtx=ftVertexer->FindPrimaryVertex(&trkArray,selectedIdx);
1985        if (pvtx) {
1986           if (pvtx->GetStatus()) {
1987              fesd->SetPrimaryVertexTPC(pvtx);
1988              for (Int_t i=0; i<ntracks; i++) {
1989                  AliESDtrack *t = fesd->GetTrack(i);
1990                  Double_t x[3]; t->GetXYZ(x);
1991                  Double_t b[3]; AliTracker::GetBxByBz(x,b);
1992                  t->RelateToVertexTPCBxByBz(pvtx, b, kVeryBig);
1993              } 
1994           }
1995           delete pvtx; pvtx=NULL;
1996        }
1997
1998     }
1999     delete[] selectedIdx;
2000
2001     if(fDiamondProfile && fDiamondProfile->GetXRes()<kRadius) fesd->SetDiamond(fDiamondProfile);
2002     else fesd->SetDiamond(fDiamondProfileSPD);
2003
2004     if (fRunV0Finder) {
2005        // V0 finding
2006        AliV0vertexer vtxer;
2007        vtxer.Tracks2V0vertices(fesd);
2008
2009        if (fRunCascadeFinder) {
2010           // Cascade finding
2011           AliCascadeVertexer cvtxer;
2012           cvtxer.V0sTracks2CascadeVertices(fesd);
2013        }
2014     }
2015  
2016     // RS run updated trackleter: since we want to mark the clusters used by tracks and also mark the 
2017     // tracks interpreted as primary, this step should be done in the very end, when full 
2018     // ESD info is available (particulalry, V0s)
2019     // vertex finder
2020     if (fRunMultFinder) {
2021       if (!RunMultFinder(fesd)) {
2022         if (fStopOnError) {CleanUp(); return kFALSE;}
2023       }
2024     }
2025
2026     // write ESD
2027     if (fCleanESD) CleanESD(fesd);
2028
2029   if (fRunQA && IsInTasks(AliQAv1::kESDS)) {
2030     AliQAManager::QAManager()->SetEventSpecie(fRecoParam.GetEventSpecie()) ;
2031     AliQAManager::QAManager()->RunOneEvent(fesd, fhltesd) ; 
2032   }
2033   if (fRunGlobalQA) {
2034     AliQADataMaker *qadm = AliQAManager::QAManager()->GetQADataMaker(AliQAv1::kGLOBAL);
2035       qadm->SetEventSpecie(fRecoParam.GetEventSpecie()) ;
2036     if (qadm && IsInTasks(AliQAv1::kESDS))
2037       qadm->Exec(AliQAv1::kESDS, fesd);
2038   }
2039
2040   // copy HLT decision from HLTesd to esd
2041   // the most relevant information is stored in a reduced container in the esd,
2042   // while the full information can be found in the HLTesd
2043   TObject* pHLTSrc=fhltesd->FindListObject(AliESDHLTDecision::Name());
2044   TObject* pHLTTgt=fesd->FindListObject(AliESDHLTDecision::Name());
2045   if (pHLTSrc && pHLTTgt) {
2046     pHLTSrc->Copy(*pHLTTgt);
2047   }
2048
2049     if (fWriteESDfriend) 
2050       fesd->GetESDfriend(fesdf);
2051
2052     ftree->Fill();
2053     if (fWriteESDfriend) ftreeF->Fill();
2054
2055     // Auto-save the ESD tree in case of prompt reco @P2
2056     if (fRawReader && fRawReader->UseAutoSaveESD()) {
2057       ftree->AutoSave("SaveSelf");
2058       if (fWriteESDfriend) ftreeF->AutoSave("SaveSelf");
2059       TFile *friendfile = (TFile *)(gROOT->GetListOfFiles()->FindObject("AliESDfriends.root"));
2060       if (friendfile) friendfile->Save();
2061     }
2062
2063     // write HLT ESD
2064     fhlttree->Fill();
2065
2066     // call AliEVE
2067     if (fRunAliEVE) RunAliEVE();
2068
2069     fesd->Reset();
2070     fhltesd->Reset();
2071     if (fWriteESDfriend) {
2072       fesdf->~AliESDfriend();
2073       new (fesdf) AliESDfriend(); // Reset...
2074     }
2075  
2076     gSystem->GetProcInfo(&procInfo);
2077     Long_t dMres=(procInfo.fMemResident-oldMres)/1024;
2078     Long_t dMvir=(procInfo.fMemVirtual-oldMvir)/1024;
2079     Float_t dCPU=procInfo.fCpuUser+procInfo.fCpuSys-oldCPU;
2080     aveDMres+=(dMres-aveDMres)/(iEvent-fFirstEvent+1);
2081     aveDMvir+=(dMvir-aveDMvir)/(iEvent-fFirstEvent+1);
2082     aveDCPU+=(dCPU-aveDCPU)/(iEvent-fFirstEvent+1);
2083     AliInfo(Form("======================= End Event %d: Res %d(%3d <%3d>) Vir %d(%3d <%3d>) CPU %5.2f <%5.2f> ===================",
2084                  iEvent, procInfo.fMemResident/1024, dMres, aveDMres, procInfo.fMemVirtual/1024, dMvir, aveDMvir, dCPU, aveDCPU));
2085     oldMres=procInfo.fMemResident;
2086     oldMvir=procInfo.fMemVirtual;
2087     oldCPU=procInfo.fCpuUser+procInfo.fCpuSys;
2088   
2089     fEventInfo.Reset();
2090     for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
2091       if (fReconstructor[iDet]) {
2092         fReconstructor[iDet]->SetRecoParam(NULL);
2093         fReconstructor[iDet]->SetEventInfo(NULL);
2094       }
2095       if (fTracker[iDet]) fTracker[iDet]->SetEventInfo(NULL);
2096     }
2097         
2098   if (fRunQA || fRunGlobalQA) 
2099     AliQAManager::QAManager()->Increment() ; 
2100   
2101     return kTRUE;
2102 }
2103
2104 //_____________________________________________________________________________
2105 void AliReconstruction::SlaveTerminate()
2106 {
2107   // Finalize the run on the slave side
2108   // Called after the exit
2109   // from the event loop
2110   AliCodeTimerAuto("",0);
2111
2112   if (fIsNewRunLoader) { // galice.root didn't exist
2113     fRunLoader->WriteHeader("OVERWRITE");
2114     fRunLoader->CdGAFile();
2115     fRunLoader->Write(0, TObject::kOverwrite);
2116   }
2117
2118   const TMap *cdbMap = AliCDBManager::Instance()->GetStorageMap();       
2119   const TList *cdbList = AliCDBManager::Instance()->GetRetrievedIds();   
2120                  
2121    TMap *cdbMapCopy = new TMap(cdbMap->GetEntries());    
2122    cdbMapCopy->SetOwner(1);      
2123    cdbMapCopy->SetName("cdbMap");        
2124    TIter iter(cdbMap->GetTable());       
2125          
2126    TPair* pair = 0;      
2127    while((pair = dynamic_cast<TPair*> (iter.Next()))){   
2128          TObjString* keyStr = dynamic_cast<TObjString*> (pair->Key());   
2129          TObjString* valStr = dynamic_cast<TObjString*> (pair->Value());         
2130          cdbMapCopy->Add(new TObjString(keyStr->GetName()), new TObjString(valStr->GetName()));  
2131    }     
2132          
2133    TList *cdbListCopy = new TList();     
2134    cdbListCopy->SetOwner(1);     
2135    cdbListCopy->SetName("cdbList");      
2136          
2137    TIter iter2(cdbList);         
2138          
2139         AliCDBId* id=0;
2140         while((id = dynamic_cast<AliCDBId*> (iter2.Next()))){    
2141          cdbListCopy->Add(new TObjString(id->ToString().Data()));        
2142    }     
2143          
2144    ftree->GetUserInfo()->Add(cdbMapCopy);        
2145    ftree->GetUserInfo()->Add(cdbListCopy);
2146
2147
2148   ffile->cd();
2149
2150   // we want to have only one tree version number
2151   ftree->Write(ftree->GetName(),TObject::kOverwrite);
2152   fhlttree->Write(fhlttree->GetName(),TObject::kOverwrite);
2153
2154   if (fWriteESDfriend) {
2155     ffileF->cd();
2156     ftreeF->Write(ftreeF->GetName(),TObject::kOverwrite);
2157   }
2158
2159 // Finish with Plane Efficiency evaluation: before of CleanUp !!!
2160   if (fRunPlaneEff && !FinishPlaneEff()) {
2161    AliWarning("Finish PlaneEff evaluation failed");
2162   }
2163
2164   // End of cycle for the in-loop  
2165
2166   if (fRunQA || fRunGlobalQA) {
2167     AliQAManager::QAManager()->EndOfCycle() ;
2168     if (fInput &&
2169         !fProofOutputLocation.IsNull() &&
2170         fProofOutputArchive.IsNull() &&
2171         !fProofOutputDataset) {
2172       TString qaOutputFile(Form("%sMerged.%s.Data.root",
2173                                 fProofOutputLocation.Data(),
2174                                 AliQAv1::GetQADataFileName()));
2175       TProofOutputFile *qaProofFile = new TProofOutputFile(Form("Merged.%s.Data.root",
2176                                                                 AliQAv1::GetQADataFileName()));
2177       qaProofFile->SetOutputFileName(qaOutputFile.Data());
2178       if (AliDebugLevel() > 0) qaProofFile->Dump();
2179       fOutput->Add(qaProofFile);
2180       MergeQA(qaProofFile->GetFileName());
2181     }
2182     else {
2183       MergeQA();
2184     }
2185   }
2186
2187   gROOT->cd();
2188   CleanUp();
2189
2190   if (fInput) {
2191     if (!fProofOutputFileName.IsNull() &&
2192         !fProofOutputLocation.IsNull() &&
2193         fProofOutputDataset &&
2194         !fProofOutputArchive.IsNull()) {
2195       TProofOutputFile *zipProofFile = new TProofOutputFile(fProofOutputFileName.Data(),
2196                                                             "DROV",
2197                                                             fProofOutputLocation.Data());
2198       if (AliDebugLevel() > 0) zipProofFile->Dump();
2199       fOutput->Add(zipProofFile);
2200       TString fileList(fProofOutputArchive.Data());
2201       fileList.ReplaceAll(","," ");
2202       TString command;
2203 #if ROOT_SVN_REVISION >= 30174
2204       command.Form("zip -n root %s/%s %s",zipProofFile->GetDir(kTRUE),zipProofFile->GetFileName(),fileList.Data());
2205 #else
2206       command.Form("zip -n root %s/%s %s",zipProofFile->GetDir(),zipProofFile->GetFileName(),fileList.Data());
2207 #endif
2208       AliInfo(Form("Executing: %s",command.Data()));
2209       gSystem->Exec(command.Data());
2210     }
2211   }
2212 }
2213     
2214 //_____________________________________________________________________________
2215 void AliReconstruction::Terminate()
2216 {
2217   // Create tags for the events in the ESD tree (the ESD tree is always present)
2218   // In case of empty events the tags will contain dummy values
2219   AliCodeTimerAuto("",0);
2220
2221   // Do not call the ESD tag creator in case of PROOF-based reconstruction
2222   if (!fInput) {
2223     AliESDTagCreator *esdtagCreator = new AliESDTagCreator();
2224     esdtagCreator->CreateESDTags(fFirstEvent,fLastEvent,fGRPData, AliQAv1::Instance()->GetQA(), AliQAv1::Instance()->GetEventSpecies(), AliQAv1::kNDET, AliRecoParam::kNSpecies);
2225     delete esdtagCreator;
2226   }
2227
2228   // Cleanup of CDB manager: cache and active storages!
2229   AliCDBManager::Instance()->ClearCache();
2230 }
2231
2232 //_____________________________________________________________________________
2233 Bool_t AliReconstruction::RunLocalEventReconstruction(const TString& detectors)
2234 {
2235 // run the local reconstruction
2236
2237   static Int_t eventNr=0;
2238   AliCodeTimerAuto("",0)
2239
2240   TString detStr = detectors;
2241   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
2242     if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
2243     AliReconstructor* reconstructor = GetReconstructor(iDet);
2244     if (!reconstructor) continue;
2245     AliLoader* loader = fLoader[iDet];
2246     // Matthias April 2008: temporary fix to run HLT reconstruction
2247     // although the HLT loader is missing
2248     if (strcmp(fgkDetectorName[iDet], "HLT")==0) {
2249       if (fRawReader) {
2250         reconstructor->Reconstruct(fRawReader, NULL);
2251       } else {
2252         TTree* dummy=NULL;
2253         reconstructor->Reconstruct(dummy, NULL);
2254       }
2255       continue;
2256     }
2257     if (!loader) {
2258       AliWarning(Form("No loader is defined for %s!",fgkDetectorName[iDet]));
2259       continue;
2260     }
2261     // conversion of digits
2262     if (fRawReader && reconstructor->HasDigitConversion()) {
2263       AliInfo(Form("converting raw data digits into root objects for %s", 
2264                    fgkDetectorName[iDet]));
2265 //      AliCodeTimerAuto(Form("converting raw data digits into root objects for %s", 
2266 //                            fgkDetectorName[iDet]),0);
2267       loader->LoadDigits("update");
2268       loader->CleanDigits();
2269       loader->MakeDigitsContainer();
2270       TTree* digitsTree = loader->TreeD();
2271       reconstructor->ConvertDigits(fRawReader, digitsTree);
2272       loader->WriteDigits("OVERWRITE");
2273       loader->UnloadDigits();
2274     }
2275     // local reconstruction
2276     AliInfo(Form("running reconstruction for %s", fgkDetectorName[iDet]));
2277     //AliCodeTimerAuto(Form("running reconstruction for %s", fgkDetectorName[iDet]),0);
2278     loader->LoadRecPoints("update");
2279     loader->CleanRecPoints();
2280     loader->MakeRecPointsContainer();
2281     TTree* clustersTree = loader->TreeR();
2282     if (fRawReader && !reconstructor->HasDigitConversion()) {
2283       reconstructor->Reconstruct(fRawReader, clustersTree);
2284     } else {
2285       loader->LoadDigits("read");
2286       TTree* digitsTree = loader->TreeD();
2287       if (!digitsTree) {
2288         AliError(Form("Can't get the %s digits tree", fgkDetectorName[iDet]));
2289         if (fStopOnError) 
2290           return kFALSE;
2291       } else {
2292         reconstructor->Reconstruct(digitsTree, clustersTree);
2293         if (fRunQA && IsInTasks(AliQAv1::kDIGITSR)) {
2294           AliQAManager::QAManager()->SetEventSpecie(fRecoParam.GetEventSpecie()) ;
2295           AliQAManager::QAManager()->RunOneEventInOneDetector(iDet, digitsTree) ; 
2296         }
2297       }
2298       loader->UnloadDigits();
2299     }
2300                 if (fRunQA && IsInTasks(AliQAv1::kRECPOINTS)) {
2301       AliQAManager::QAManager()->SetEventSpecie(fRecoParam.GetEventSpecie()) ;
2302                         AliQAManager::QAManager()->RunOneEventInOneDetector(iDet, clustersTree) ; 
2303     }
2304     loader->WriteRecPoints("OVERWRITE");
2305     loader->UnloadRecPoints();
2306     AliSysInfo::AddStamp(Form("LRec%s_%d",fgkDetectorName[iDet],eventNr), iDet,1,eventNr);
2307   }
2308   IsSelected("CTP", detStr);
2309   if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
2310     AliError(Form("the following detectors were not found: %s",
2311                   detStr.Data()));
2312     if (fStopOnError) 
2313       return kFALSE;
2314   }
2315   eventNr++;
2316   return kTRUE;
2317 }
2318 //_____________________________________________________________________________
2319 Bool_t AliReconstruction::RunSPDTrackleting(AliESDEvent*& esd)
2320 {
2321 // run the SPD trackleting (for SPD efficiency purpouses)
2322
2323   AliCodeTimerAuto("",0)
2324
2325   Double_t vtxPos[3] = {0, 0, 0};
2326   Double_t vtxErr[3] = {0.0, 0.0, 0.0};
2327 /*
2328   TArrayF mcVertex(3);
2329   // if(MC)
2330   if (fRunLoader->GetHeader() && fRunLoader->GetHeader()->GenEventHeader()) {
2331     fRunLoader->GetHeader()->GenEventHeader()->PrimaryVertex(mcVertex);
2332     for (Int_t i = 0; i < 3; i++) vtxPos[i] = mcVertex[i];
2333   }
2334 */
2335   const AliESDVertex *vertex = esd->GetVertex();
2336   if(!vertex){
2337     AliWarning("Vertex not found");
2338     return kFALSE;
2339   }
2340   vertex->GetXYZ(vtxPos);
2341   vertex->GetSigmaXYZ(vtxErr);
2342   if (fSPDTrackleter) {
2343     AliInfo("running the SPD Trackleter for Plane Efficiency Evaluation");
2344
2345     // load clusters
2346     fLoader[0]->LoadRecPoints("read");
2347     TTree* tree = fLoader[0]->TreeR();
2348     if (!tree) {
2349       AliError("Can't get the ITS cluster tree");
2350       return kFALSE;
2351     }
2352     fSPDTrackleter->LoadClusters(tree);
2353     fSPDTrackleter->SetVertex(vtxPos, vtxErr);
2354     // run trackleting
2355     if (fSPDTrackleter->Clusters2Tracks(esd) != 0) {
2356       AliWarning("AliITSTrackleterSPDEff Clusters2Tracks failed");
2357      // fLoader[0]->UnloadRecPoints();
2358       return kFALSE;
2359     }
2360 //fSPDTrackleter->UnloadRecPoints();
2361   } else {
2362     AliWarning("SPDTrackleter not available");
2363     return kFALSE;
2364   }
2365   return kTRUE;
2366 }
2367
2368 //_____________________________________________________________________________
2369 Bool_t AliReconstruction::RunVertexFinder(AliESDEvent*& esd)
2370 {
2371 // run the barrel tracking
2372
2373   AliCodeTimerAuto("",0)
2374
2375   AliVertexer *vertexer = CreateVertexer();
2376   if (!vertexer) return kFALSE;
2377
2378   AliInfo(Form("running the ITS vertex finder: %s",vertexer->ClassName()));
2379   AliESDVertex* vertex = NULL;
2380   if (fLoader[0]) {
2381     fLoader[0]->LoadRecPoints();
2382     TTree* cltree = fLoader[0]->TreeR();
2383     if (cltree) {
2384       if(fDiamondProfileSPD) vertexer->SetVtxStart(fDiamondProfileSPD);
2385       vertex = vertexer->FindVertexForCurrentEvent(cltree);
2386     }
2387     else {
2388       AliError("Can't get the ITS cluster tree");
2389     }
2390     fLoader[0]->UnloadRecPoints();
2391   }
2392   else {
2393     AliError("Can't get the ITS loader");
2394   }
2395   if(!vertex){
2396     AliWarning("Vertex not found");
2397     vertex = new AliESDVertex();
2398     vertex->SetName("default");
2399   }
2400   else {
2401     vertex->SetName("reconstructed");
2402   }
2403
2404   Double_t vtxPos[3];
2405   Double_t vtxErr[3];
2406   vertex->GetXYZ(vtxPos);
2407   vertex->GetSigmaXYZ(vtxErr);
2408
2409   esd->SetPrimaryVertexSPD(vertex);
2410   AliESDVertex *vpileup = NULL;
2411   Int_t novertices = 0;
2412   vpileup = vertexer->GetAllVertices(novertices);
2413   if(novertices>1){
2414     for (Int_t kk=1; kk<novertices; kk++)esd->AddPileupVertexSPD(&vpileup[kk]);
2415   }
2416   /*
2417   // if SPD multiplicity has been determined, it is stored in the ESD
2418   AliMultiplicity *mult = vertexer->GetMultiplicity();
2419   if(mult)esd->SetMultiplicity(mult);
2420   */
2421   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
2422     if (fTracker[iDet]) fTracker[iDet]->SetVertex(vtxPos, vtxErr);
2423   }  
2424   delete vertex;
2425
2426   delete vertexer;
2427
2428   return kTRUE;
2429 }
2430
2431 //_____________________________________________________________________________
2432 Bool_t AliReconstruction::RunMultFinder(AliESDEvent*& esd)
2433 {
2434   // run the trackleter for multiplicity study
2435
2436   AliCodeTimerAuto("",0)
2437
2438   AliTrackleter *trackleter = CreateMultFinder();
2439   if (!trackleter) return kFALSE;
2440
2441   AliInfo(Form("running the ITS multiplicity finder: %s",trackleter->ClassName()));
2442
2443   if (fLoader[0]) {
2444     fLoader[0]->LoadRecPoints();
2445     TTree* cltree = fLoader[0]->TreeR();
2446     if (cltree) {
2447       trackleter->Reconstruct(esd,cltree);
2448       AliMultiplicity *mult = trackleter->GetMultiplicity();
2449       if(mult) esd->SetMultiplicity(mult);
2450     }
2451     else {
2452       AliError("Can't get the ITS cluster tree");
2453     }
2454     fLoader[0]->UnloadRecPoints();
2455   }
2456   else {
2457     AliError("Can't get the ITS loader");
2458   }
2459
2460   delete trackleter;
2461
2462   return kTRUE;
2463 }
2464
2465 //_____________________________________________________________________________
2466 Bool_t AliReconstruction::RunHLTTracking(AliESDEvent*& esd)
2467 {
2468 // run the HLT barrel tracking
2469
2470   AliCodeTimerAuto("",0)
2471
2472   if (!fRunLoader) {
2473     AliError("Missing runLoader!");
2474     return kFALSE;
2475   }
2476
2477   AliInfo("running HLT tracking");
2478
2479   // Get a pointer to the HLT reconstructor
2480   AliReconstructor *reconstructor = GetReconstructor(kNDetectors-1);
2481   if (!reconstructor) return kFALSE;
2482
2483   // TPC + ITS
2484   for (Int_t iDet = 1; iDet >= 0; iDet--) {
2485     TString detName = fgkDetectorName[iDet];
2486     AliDebug(1, Form("%s HLT tracking", detName.Data()));
2487     reconstructor->SetOption(detName.Data());
2488     AliTracker *tracker = reconstructor->CreateTracker();
2489     if (!tracker) {
2490       AliWarning(Form("couldn't create a HLT tracker for %s", detName.Data()));
2491       if (fStopOnError) return kFALSE;
2492       continue;
2493     }
2494     Double_t vtxPos[3];
2495     Double_t vtxErr[3]={0.005,0.005,0.010};
2496     const AliESDVertex *vertex = esd->GetVertex();
2497     vertex->GetXYZ(vtxPos);
2498     tracker->SetVertex(vtxPos,vtxErr);
2499     if(iDet != 1) {
2500       fLoader[iDet]->LoadRecPoints("read");
2501       TTree* tree = fLoader[iDet]->TreeR();
2502       if (!tree) {
2503         AliError(Form("Can't get the %s cluster tree", detName.Data()));
2504         return kFALSE;
2505       }
2506       tracker->LoadClusters(tree);
2507     }
2508     if (tracker->Clusters2Tracks(esd) != 0) {
2509       AliError(Form("HLT %s Clusters2Tracks failed", fgkDetectorName[iDet]));
2510       return kFALSE;
2511     }
2512     if(iDet != 1) {
2513       tracker->UnloadClusters();
2514     }
2515     delete tracker;
2516   }
2517
2518   return kTRUE;
2519 }
2520
2521 //_____________________________________________________________________________
2522 Bool_t AliReconstruction::RunMuonTracking(AliESDEvent*& esd)
2523 {
2524 // run the muon spectrometer tracking
2525
2526   AliCodeTimerAuto("",0)
2527
2528   if (!fRunLoader) {
2529     AliError("Missing runLoader!");
2530     return kFALSE;
2531   }
2532   Int_t iDet = 7; // for MUON
2533
2534   AliInfo("is running...");
2535
2536   // Get a pointer to the MUON reconstructor
2537   AliReconstructor *reconstructor = GetReconstructor(iDet);
2538   if (!reconstructor) return kFALSE;
2539
2540   
2541   TString detName = fgkDetectorName[iDet];
2542   AliDebug(1, Form("%s tracking", detName.Data()));
2543   AliTracker *tracker =  reconstructor->CreateTracker();
2544   if (!tracker) {
2545     AliWarning(Form("couldn't create a tracker for %s", detName.Data()));
2546     return kFALSE;
2547   }
2548      
2549   // read RecPoints
2550   fLoader[iDet]->LoadRecPoints("read");  
2551
2552   tracker->LoadClusters(fLoader[iDet]->TreeR());
2553   
2554   Int_t rv = tracker->Clusters2Tracks(esd);
2555   
2556   fLoader[iDet]->UnloadRecPoints();
2557
2558   tracker->UnloadClusters();
2559   
2560   delete tracker;
2561   
2562   if ( rv )
2563   {
2564     AliError(Form("%s Clusters2Tracks failed", fgkDetectorName[iDet]));
2565     return kFALSE;
2566   }
2567   
2568   return kTRUE;
2569 }
2570
2571
2572 //_____________________________________________________________________________
2573 Bool_t AliReconstruction::RunTracking(AliESDEvent*& esd,AliESDpid &PID)
2574 {
2575 // run the barrel tracking
2576   static Int_t eventNr=0;
2577   AliCodeTimerAuto("",0)
2578
2579   AliInfo("running tracking");
2580
2581   // Set the event info which is used
2582   // by the trackers in order to obtain
2583   // information about read-out detectors,
2584   // trigger etc.
2585   AliDebug(1, "Setting event info");
2586   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
2587     if (!fTracker[iDet]) continue;
2588     fTracker[iDet]->SetEventInfo(&fEventInfo);
2589   }
2590
2591   //Fill the ESD with the T0 info (will be used by the TOF) 
2592   if (fReconstructor[11] && fLoader[11]) {
2593     fLoader[11]->LoadRecPoints("READ");
2594     TTree *treeR = fLoader[11]->TreeR();
2595     if (treeR) {
2596       GetReconstructor(11)->FillESD((TTree *)NULL,treeR,esd);
2597     }
2598   }
2599
2600   // pass 1: TPC + ITS inwards
2601   for (Int_t iDet = 1; iDet >= 0; iDet--) {
2602     if (!fTracker[iDet]) continue;
2603     AliDebug(1, Form("%s tracking", fgkDetectorName[iDet]));
2604
2605     // load clusters
2606     fLoader[iDet]->LoadRecPoints("read");
2607     AliSysInfo::AddStamp(Form("RLoadCluster%s_%d",fgkDetectorName[iDet],eventNr),iDet,1, eventNr);
2608     TTree* tree = fLoader[iDet]->TreeR();
2609     if (!tree) {
2610       AliError(Form("Can't get the %s cluster tree", fgkDetectorName[iDet]));
2611       return kFALSE;
2612     }
2613     fTracker[iDet]->LoadClusters(tree);
2614     AliSysInfo::AddStamp(Form("TLoadCluster%s_%d",fgkDetectorName[iDet],eventNr), iDet,2, eventNr);
2615     // run tracking
2616     if (fTracker[iDet]->Clusters2Tracks(esd) != 0) {
2617       AliError(Form("%s Clusters2Tracks failed", fgkDetectorName[iDet]));
2618       return kFALSE;
2619     }
2620     // preliminary PID in TPC needed by the ITS tracker
2621     if (iDet == 1) {
2622       GetReconstructor(1)->FillESD((TTree*)NULL, (TTree*)NULL, esd);
2623       PID.MakePID(esd,kTRUE);
2624     } 
2625     AliSysInfo::AddStamp(Form("Tracking0%s_%d",fgkDetectorName[iDet],eventNr), iDet,3,eventNr);
2626   }
2627
2628   // pass 2: ALL backwards
2629
2630   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
2631     if (!fTracker[iDet]) continue;
2632     AliDebug(1, Form("%s back propagation", fgkDetectorName[iDet]));
2633
2634     // load clusters
2635     if (iDet > 1) {     // all except ITS, TPC
2636       TTree* tree = NULL;
2637       fLoader[iDet]->LoadRecPoints("read");
2638       AliSysInfo::AddStamp(Form("RLoadCluster0%s_%d",fgkDetectorName[iDet],eventNr), iDet,1, eventNr);
2639       tree = fLoader[iDet]->TreeR();
2640       if (!tree) {
2641         AliError(Form("Can't get the %s cluster tree", fgkDetectorName[iDet]));
2642         return kFALSE;
2643       }
2644       fTracker[iDet]->LoadClusters(tree); 
2645       AliSysInfo::AddStamp(Form("TLoadCluster0%s_%d",fgkDetectorName[iDet],eventNr), iDet,2, eventNr);
2646     }
2647
2648     // run tracking
2649     if (iDet>1) // start filling residuals for the "outer" detectors
2650       if (fRunGlobalQA) {
2651         AliTracker::SetFillResiduals(fRecoParam.GetEventSpecie(), kTRUE);     
2652         TObjArray ** arr = AliTracker::GetResidualsArray() ; 
2653         if (arr) {
2654           AliRecoParam::EventSpecie_t es=fRecoParam.GetEventSpecie();
2655           TObjArray * elem = arr[AliRecoParam::AConvert(es)];
2656           if ( elem && (! elem->At(0)) ) {
2657             AliQADataMaker *qadm = AliQAManager::QAManager()->GetQADataMaker(AliQAv1::kGLOBAL);
2658             if (qadm) qadm->InitRecPointsForTracker() ; 
2659           }
2660         }
2661       }
2662     if (fTracker[iDet]->PropagateBack(esd) != 0) {
2663       AliError(Form("%s backward propagation failed", fgkDetectorName[iDet]));
2664       //      return kFALSE;
2665     }
2666
2667     // unload clusters
2668     if (iDet > 3) {     // all except ITS, TPC, TRD and TOF
2669       fTracker[iDet]->UnloadClusters();
2670       fLoader[iDet]->UnloadRecPoints();
2671     }
2672     // updated PID in TPC needed by the ITS tracker -MI
2673     if (iDet == 1) {
2674       //GetReconstructor(1)->FillESD((TTree*)NULL, (TTree*)NULL, esd);
2675       //AliESDpid::MakePID(esd);
2676       PID.MakePID(esd,kTRUE);
2677     }
2678     AliSysInfo::AddStamp(Form("Tracking1%s_%d",fgkDetectorName[iDet],eventNr), iDet,3, eventNr);
2679   }
2680   //stop filling residuals for the "outer" detectors
2681   if (fRunGlobalQA) AliTracker::SetFillResiduals(fRecoParam.GetEventSpecie(), kFALSE);     
2682
2683   // pass 3: TRD + TPC + ITS refit inwards
2684
2685   for (Int_t iDet = 2; iDet >= 0; iDet--) {
2686     if (!fTracker[iDet]) continue;
2687     AliDebug(1, Form("%s inward refit", fgkDetectorName[iDet]));
2688
2689     // run tracking
2690     if (iDet<2) // start filling residuals for TPC and ITS
2691       if (fRunGlobalQA) {
2692         AliTracker::SetFillResiduals(fRecoParam.GetEventSpecie(), kTRUE);     
2693         TObjArray ** arr = AliTracker::GetResidualsArray() ; 
2694         if (arr) {
2695           AliRecoParam::EventSpecie_t es=fRecoParam.GetEventSpecie();
2696           TObjArray * elem = arr[AliRecoParam::AConvert(es)];
2697           if ( elem && (! elem->At(0)) ) {
2698             AliQADataMaker *qadm = AliQAManager::QAManager()->GetQADataMaker(AliQAv1::kGLOBAL);
2699             if (qadm) qadm->InitRecPointsForTracker() ; 
2700           }
2701         }
2702       }
2703     
2704     if (fTracker[iDet]->RefitInward(esd) != 0) {
2705       AliError(Form("%s inward refit failed", fgkDetectorName[iDet]));
2706       //      return kFALSE;
2707     }
2708     // run postprocessing
2709     if (fTracker[iDet]->PostProcess(esd) != 0) {
2710       AliError(Form("%s postprocessing failed", fgkDetectorName[iDet]));
2711       //      return kFALSE;
2712     }
2713     AliSysInfo::AddStamp(Form("Tracking2%s_%d",fgkDetectorName[iDet],eventNr), iDet,3, eventNr);
2714   }
2715
2716   // write space-points to the ESD in case alignment data output
2717   // is switched on
2718   if (fWriteAlignmentData)
2719     WriteAlignmentData(esd);
2720
2721   for (Int_t iDet = 3; iDet >= 0; iDet--) {
2722     if (!fTracker[iDet]) continue;
2723     // unload clusters
2724     fTracker[iDet]->UnloadClusters();
2725     AliSysInfo::AddStamp(Form("TUnloadCluster%s_%d",fgkDetectorName[iDet],eventNr), iDet,4, eventNr);
2726     fLoader[iDet]->UnloadRecPoints();
2727     AliSysInfo::AddStamp(Form("RUnloadCluster%s_%d",fgkDetectorName[iDet],eventNr), iDet,5, eventNr);
2728   }
2729   // stop filling residuals for TPC and ITS
2730   if (fRunGlobalQA) AliTracker::SetFillResiduals(fRecoParam.GetEventSpecie(), kFALSE);     
2731
2732   eventNr++;
2733   return kTRUE;
2734 }
2735
2736 //_____________________________________________________________________________
2737 Bool_t AliReconstruction::CleanESD(AliESDEvent *esd){
2738   //
2739   // Remove the data which are not needed for the physics analysis.
2740   //
2741
2742   Int_t nTracks=esd->GetNumberOfTracks();
2743   Int_t nV0s=esd->GetNumberOfV0s();
2744   AliInfo
2745   (Form("Number of ESD tracks and V0s before cleaning: %d %d",nTracks,nV0s));
2746
2747   Float_t cleanPars[]={fV0DCAmax,fV0CsPmin,fDmax,fZmax};
2748   Bool_t rc=esd->Clean(cleanPars);
2749
2750   nTracks=esd->GetNumberOfTracks();
2751   nV0s=esd->GetNumberOfV0s();
2752   AliInfo
2753   (Form("Number of ESD tracks and V0s after cleaning %d %d",nTracks,nV0s));
2754
2755   return rc;
2756 }
2757
2758 //_____________________________________________________________________________
2759 Bool_t AliReconstruction::FillESD(AliESDEvent*& esd, const TString& detectors)
2760 {
2761 // fill the event summary data
2762
2763   AliCodeTimerAuto("",0)
2764     static Int_t eventNr=0; 
2765   TString detStr = detectors;
2766   
2767   AliSysInfo::AddStamp(Form("FillESDb%d",eventNr), -19,-19, eventNr);
2768   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
2769   if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
2770     AliReconstructor* reconstructor = GetReconstructor(iDet);
2771     if (!reconstructor) continue;
2772     AliDebug(1, Form("filling ESD for %s", fgkDetectorName[iDet]));
2773     TTree* clustersTree = NULL;
2774     if (fLoader[iDet]) {
2775       fLoader[iDet]->LoadRecPoints("read");
2776       clustersTree = fLoader[iDet]->TreeR();
2777       if (!clustersTree) {
2778         AliError(Form("Can't get the %s clusters tree", 
2779                       fgkDetectorName[iDet]));
2780         if (fStopOnError) return kFALSE;
2781       }
2782     }
2783     if (fRawReader && !reconstructor->HasDigitConversion()) {
2784       reconstructor->FillESD(fRawReader, clustersTree, esd);
2785     } else {
2786       TTree* digitsTree = NULL;
2787       if (fLoader[iDet]) {
2788         fLoader[iDet]->LoadDigits("read");
2789         digitsTree = fLoader[iDet]->TreeD();
2790         if (!digitsTree) {
2791           AliError(Form("Can't get the %s digits tree", 
2792                         fgkDetectorName[iDet]));
2793           if (fStopOnError) return kFALSE;
2794         }
2795       }
2796       reconstructor->FillESD(digitsTree, clustersTree, esd);
2797       if (fLoader[iDet]) fLoader[iDet]->UnloadDigits();
2798     }
2799     if (fLoader[iDet]) {
2800       fLoader[iDet]->UnloadRecPoints();
2801     }
2802   }
2803   
2804   IsSelected("CTP", detStr);
2805   if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
2806     AliError(Form("the following detectors were not found: %s", 
2807                   detStr.Data()));
2808     if (fStopOnError) return kFALSE;
2809   }
2810   AliSysInfo::AddStamp(Form("FillESDe%d",eventNr), -20,-20, eventNr);
2811   eventNr++;
2812   return kTRUE;
2813 }
2814
2815 //_____________________________________________________________________________
2816 Bool_t AliReconstruction::FillTriggerESD(AliESDEvent*& esd)
2817 {
2818   // Reads the trigger decision which is
2819   // stored in Trigger.root file and fills
2820   // the corresponding esd entries
2821
2822   AliCodeTimerAuto("",0)
2823   
2824   AliInfo("Filling trigger information into the ESD");
2825
2826   if (fRawReader) {
2827     AliCTPRawStream input(fRawReader);
2828     if (!input.Next()) {
2829       AliWarning("No valid CTP (trigger) DDL raw data is found ! The trigger info is taken from the event header!");
2830     }
2831     else {
2832       if (esd->GetTriggerMask() != input.GetClassMask())
2833         AliError(Form("Invalid trigger pattern found in CTP raw-data: %llx %llx",
2834                       input.GetClassMask(),esd->GetTriggerMask()));
2835       if (esd->GetOrbitNumber() != input.GetOrbitID())
2836         AliError(Form("Invalid orbit id found in CTP raw-data: %x %x",
2837                       input.GetOrbitID(),esd->GetOrbitNumber()));
2838       if (esd->GetBunchCrossNumber() != input.GetBCID())
2839         AliError(Form("Invalid bunch-crossing id found in CTP raw-data: %x %x",
2840                       input.GetBCID(),esd->GetBunchCrossNumber()));
2841       AliESDHeader* esdheader = esd->GetHeader();
2842       esdheader->SetL0TriggerInputs(input.GetL0Inputs());
2843       esdheader->SetL1TriggerInputs(input.GetL1Inputs());
2844       esdheader->SetL2TriggerInputs(input.GetL2Inputs());
2845       // IR
2846       UInt_t orbit=input.GetOrbitID();
2847        for(Int_t i=0 ; i<input.GetNIRs() ; i++ )
2848           if(TMath::Abs(Int_t(orbit-(input.GetIR(i))->GetOrbit()))<=1){
2849              esdheader->AddTriggerIR(input.GetIR(i));
2850           }
2851     }
2852   }
2853   return kTRUE;
2854 }
2855 //_____________________________________________________________________________
2856 Bool_t AliReconstruction::FillTriggerScalers(AliESDEvent*& esd)
2857 {
2858   //Scalers
2859   //fRunScalers->Print();
2860   if(fRunScalers && fRunScalers->CheckRunScalers()){
2861      AliTimeStamp* timestamp = new AliTimeStamp(esd->GetOrbitNumber(), esd->GetPeriodNumber(), esd->GetBunchCrossNumber());
2862      //AliTimeStamp* timestamp = new AliTimeStamp(10308000, 0, (ULong64_t)486238);
2863      AliESDHeader* esdheader = fesd->GetHeader();
2864      for(Int_t i=0;i<50;i++){
2865           if((1ull<<i) & esd->GetTriggerMask()){
2866           AliTriggerScalersESD* scalesd = fRunScalers->GetScalersForEventClass( timestamp, i+1);
2867           if(scalesd)esdheader->SetTriggerScalersRecord(scalesd);
2868         }
2869      }
2870   }
2871   return kTRUE;
2872 }
2873 //_____________________________________________________________________________
2874 Bool_t AliReconstruction::FillRawEventHeaderESD(AliESDEvent*& esd)
2875 {
2876   // 
2877   // Filling information from RawReader Header
2878   // 
2879
2880   if (!fRawReader) return kFALSE;
2881
2882   AliInfo("Filling information from RawReader Header");
2883
2884   esd->SetBunchCrossNumber(fRawReader->GetBCID());
2885   esd->SetOrbitNumber(fRawReader->GetOrbitID());
2886   esd->SetPeriodNumber(fRawReader->GetPeriod());
2887
2888   esd->SetTimeStamp(fRawReader->GetTimestamp());  
2889   esd->SetEventType(fRawReader->GetType());
2890
2891   return kTRUE;
2892 }
2893
2894
2895 //_____________________________________________________________________________
2896 Bool_t AliReconstruction::IsSelected(TString detName, TString& detectors) const
2897 {
2898 // check whether detName is contained in detectors
2899 // if yes, it is removed from detectors
2900
2901   // check if all detectors are selected
2902   if ((detectors.CompareTo("ALL") == 0) ||
2903       detectors.BeginsWith("ALL ") ||
2904       detectors.EndsWith(" ALL") ||
2905       detectors.Contains(" ALL ")) {
2906     detectors = "ALL";
2907     return kTRUE;
2908   }
2909
2910   // search for the given detector
2911   Bool_t result = kFALSE;
2912   if ((detectors.CompareTo(detName) == 0) ||
2913       detectors.BeginsWith(detName+" ") ||
2914       detectors.EndsWith(" "+detName) ||
2915       detectors.Contains(" "+detName+" ")) {
2916     detectors.ReplaceAll(detName, "");
2917     result = kTRUE;
2918   }
2919
2920   // clean up the detectors string
2921   while (detectors.Contains("  ")) detectors.ReplaceAll("  ", " ");
2922   while (detectors.BeginsWith(" ")) detectors.Remove(0, 1);
2923   while (detectors.EndsWith(" ")) detectors.Remove(detectors.Length()-1, 1);
2924
2925   return result;
2926 }
2927
2928 //_____________________________________________________________________________
2929 Bool_t AliReconstruction::InitRunLoader()
2930 {
2931 // get or create the run loader
2932
2933   if (gAlice) delete gAlice;
2934   gAlice = NULL;
2935
2936   TFile *gafile = TFile::Open(fGAliceFileName.Data());
2937   //  if (!gSystem->AccessPathName(fGAliceFileName.Data())) { // galice.root exists
2938   if (gafile) { // galice.root exists
2939     gafile->Close();
2940     delete gafile;
2941
2942     // load all base libraries to get the loader classes
2943     TString libs = gSystem->GetLibraries();
2944     for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
2945       TString detName = fgkDetectorName[iDet];
2946       if (detName == "HLT") continue;
2947       if (libs.Contains("lib" + detName + "base.so")) continue;
2948       gSystem->Load("lib" + detName + "base.so");
2949     }
2950     fRunLoader = AliRunLoader::Open(fGAliceFileName.Data());
2951     if (!fRunLoader) {
2952       AliError(Form("no run loader found in file %s", fGAliceFileName.Data()));
2953       CleanUp();
2954       return kFALSE;
2955     }
2956
2957     fRunLoader->CdGAFile();
2958     fRunLoader->LoadgAlice();
2959
2960     //PH This is a temporary fix to give access to the kinematics
2961     //PH that is needed for the labels of ITS clusters
2962     fRunLoader->LoadHeader();
2963     fRunLoader->LoadKinematics();
2964
2965   } else {               // galice.root does not exist
2966     if (!fRawReader) {
2967       AliError(Form("the file %s does not exist", fGAliceFileName.Data()));
2968     }
2969     fRunLoader = AliRunLoader::Open(fGAliceFileName.Data(),
2970                                     AliConfig::GetDefaultEventFolderName(),
2971                                     "recreate");
2972     if (!fRunLoader) {
2973       AliError(Form("could not create run loader in file %s", 
2974                     fGAliceFileName.Data()));
2975       CleanUp();
2976       return kFALSE;
2977     }
2978     fIsNewRunLoader = kTRUE;
2979     fRunLoader->MakeTree("E");
2980
2981     if (fNumberOfEventsPerFile > 0)
2982       fRunLoader->SetNumberOfEventsPerFile(fNumberOfEventsPerFile);
2983     else
2984       fRunLoader->SetNumberOfEventsPerFile((UInt_t)-1);
2985   }
2986
2987   return kTRUE;
2988 }
2989
2990 //_____________________________________________________________________________
2991 AliReconstructor* AliReconstruction::GetReconstructor(Int_t iDet)
2992 {
2993 // get the reconstructor object and the loader for a detector
2994
2995   if (fReconstructor[iDet]) {
2996     if (fRecoParam.GetDetRecoParamArray(iDet) && !AliReconstructor::GetRecoParam(iDet)) {
2997       const AliDetectorRecoParam *par = fRecoParam.GetDetRecoParam(iDet);
2998       fReconstructor[iDet]->SetRecoParam(par);
2999       fReconstructor[iDet]->SetRunInfo(fRunInfo);
3000     }
3001     return fReconstructor[iDet];
3002   }
3003
3004   // load the reconstructor object
3005   TPluginManager* pluginManager = gROOT->GetPluginManager();
3006   TString detName = fgkDetectorName[iDet];
3007   TString recName = "Ali" + detName + "Reconstructor";
3008
3009   if (!fIsNewRunLoader && !fRunLoader->GetLoader(detName+"Loader") && (detName != "HLT")) return NULL;
3010
3011   AliReconstructor* reconstructor = NULL;
3012   // first check if a plugin is defined for the reconstructor
3013   TPluginHandler* pluginHandler = 
3014     pluginManager->FindHandler("AliReconstructor", detName);
3015   // if not, add a plugin for it
3016   if (!pluginHandler) {
3017     AliDebug(1, Form("defining plugin for %s", recName.Data()));
3018     TString libs = gSystem->GetLibraries();
3019     if (libs.Contains("lib" + detName + "base.so") ||
3020         (gSystem->Load("lib" + detName + "base.so") >= 0)) {
3021       pluginManager->AddHandler("AliReconstructor", detName, 
3022                                 recName, detName + "rec", recName + "()");
3023     } else {
3024       pluginManager->AddHandler("AliReconstructor", detName, 
3025                                 recName, detName, recName + "()");
3026     }
3027     pluginHandler = pluginManager->FindHandler("AliReconstructor", detName);
3028   }
3029   if (pluginHandler && (pluginHandler->LoadPlugin() == 0)) {
3030     reconstructor = (AliReconstructor*) pluginHandler->ExecPlugin(0);
3031   }
3032   if (reconstructor) {
3033     TObject* obj = fOptions.FindObject(detName.Data());
3034     if (obj) reconstructor->SetOption(obj->GetTitle());
3035     reconstructor->SetRunInfo(fRunInfo);
3036     reconstructor->Init();
3037     fReconstructor[iDet] = reconstructor;
3038   }
3039
3040   // get or create the loader
3041   if (detName != "HLT") {
3042     fLoader[iDet] = fRunLoader->GetLoader(detName + "Loader");
3043     if (!fLoader[iDet]) {
3044       AliConfig::Instance()
3045         ->CreateDetectorFolders(fRunLoader->GetEventFolder(), 
3046                                 detName, detName);
3047       // first check if a plugin is defined for the loader
3048       pluginHandler = 
3049         pluginManager->FindHandler("AliLoader", detName);
3050       // if not, add a plugin for it
3051       if (!pluginHandler) {
3052         TString loaderName = "Ali" + detName + "Loader";
3053         AliDebug(1, Form("defining plugin for %s", loaderName.Data()));
3054         pluginManager->AddHandler("AliLoader", detName, 
3055                                   loaderName, detName + "base", 
3056                                   loaderName + "(const char*, TFolder*)");
3057         pluginHandler = pluginManager->FindHandler("AliLoader", detName);
3058       }
3059       if (pluginHandler && (pluginHandler->LoadPlugin() == 0)) {
3060         fLoader[iDet] = 
3061           (AliLoader*) pluginHandler->ExecPlugin(2, detName.Data(), 
3062                                                  fRunLoader->GetEventFolder());
3063       }
3064       if (!fLoader[iDet]) {   // use default loader
3065         fLoader[iDet] = new AliLoader(detName, fRunLoader->GetEventFolder());
3066       }
3067       if (!fLoader[iDet]) {
3068         AliWarning(Form("couldn't get loader for %s", detName.Data()));
3069         if (fStopOnError) return NULL;
3070       } else {
3071         fRunLoader->AddLoader(fLoader[iDet]);
3072         fRunLoader->CdGAFile();
3073         if (gFile && !gFile->IsWritable()) gFile->ReOpen("UPDATE");
3074         fRunLoader->Write(0, TObject::kOverwrite);
3075       }
3076     }
3077   }
3078       
3079   if (fRecoParam.GetDetRecoParamArray(iDet) && !AliReconstructor::GetRecoParam(iDet)) {
3080     const AliDetectorRecoParam *par = fRecoParam.GetDetRecoParam(iDet);
3081     reconstructor->SetRecoParam(par);
3082     reconstructor->SetRunInfo(fRunInfo);
3083   }
3084   return reconstructor;
3085 }
3086
3087 //_____________________________________________________________________________
3088 AliVertexer* AliReconstruction::CreateVertexer()
3089 {
3090 // create the vertexer
3091 // Please note that the caller is the owner of the
3092 // vertexer
3093
3094   AliVertexer* vertexer = NULL;
3095   AliReconstructor* itsReconstructor = GetReconstructor(0);
3096   if (itsReconstructor && ((fRunLocalReconstruction.Contains("ITS")) || fRunTracking.Contains("ITS"))) {
3097     vertexer = itsReconstructor->CreateVertexer();
3098   }
3099   if (!vertexer) {
3100     AliWarning("couldn't create a vertexer for ITS");
3101   }
3102
3103   return vertexer;
3104 }
3105
3106 //_____________________________________________________________________________
3107 AliTrackleter* AliReconstruction::CreateMultFinder()
3108 {
3109 // create the ITS trackleter for mult. estimation
3110 // Please note that the caller is the owner of the
3111 // trackleter
3112
3113   AliTrackleter* trackleter = NULL;
3114   AliReconstructor* itsReconstructor = GetReconstructor(0);
3115   if (itsReconstructor && ((fRunLocalReconstruction.Contains("ITS")) || fRunTracking.Contains("ITS"))) {
3116     trackleter = itsReconstructor->CreateMultFinder();
3117   }
3118   if (!trackleter) {
3119     AliWarning("couldn't create a trackleter for ITS");
3120   }
3121
3122   return trackleter;
3123 }
3124
3125 //_____________________________________________________________________________
3126 Bool_t AliReconstruction::CreateTrackers(const TString& detectors)
3127 {
3128 // create the trackers
3129         AliInfo("Creating trackers");
3130
3131   TString detStr = detectors;
3132   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
3133     if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
3134     AliReconstructor* reconstructor = GetReconstructor(iDet);
3135     if (!reconstructor) continue;
3136     TString detName = fgkDetectorName[iDet];
3137     if (detName == "HLT") {
3138       fRunHLTTracking = kTRUE;
3139       continue;
3140     }
3141     if (detName == "MUON") {
3142       fRunMuonTracking = kTRUE;
3143       continue;
3144     }
3145
3146     fTracker[iDet] = reconstructor->CreateTracker();
3147     if (!fTracker[iDet] && (iDet < 7)) {
3148       AliWarning(Form("couldn't create a tracker for %s", detName.Data()));
3149       if (fStopOnError) return kFALSE;
3150     }
3151     AliSysInfo::AddStamp(Form("LTracker%s",fgkDetectorName[iDet]), iDet,0);
3152   }
3153
3154   return kTRUE;
3155 }
3156
3157 //_____________________________________________________________________________
3158 void AliReconstruction::CleanUp()
3159 {
3160 // delete trackers and the run loader and close and delete the file
3161
3162   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
3163     delete fReconstructor[iDet];
3164     fReconstructor[iDet] = NULL;
3165     fLoader[iDet] = NULL;
3166     delete fTracker[iDet];
3167     fTracker[iDet] = NULL;
3168   }
3169   delete fRunInfo;
3170   fRunInfo = NULL;
3171
3172   delete fSPDTrackleter;
3173   fSPDTrackleter = NULL;
3174
3175   delete ftVertexer;
3176   ftVertexer = NULL;
3177   
3178   delete fRunLoader;
3179   fRunLoader = NULL;
3180   delete fRawReader;
3181   fRawReader = NULL;
3182   delete fParentRawReader;
3183   fParentRawReader=NULL;
3184
3185   if (ffile) {
3186     ffile->Close();
3187     delete ffile;
3188     ffile = NULL;
3189   }
3190
3191   if (AliQAManager::QAManager())
3192     AliQAManager::QAManager()->ShowQA() ; 
3193   AliQAManager::Destroy() ; 
3194   
3195 }
3196
3197 void AliReconstruction::WriteAlignmentData(AliESDEvent* esd)
3198 {
3199   // Write space-points which are then used in the alignment procedures
3200   // For the moment only ITS, TPC, TRD and TOF
3201
3202   Int_t ntracks = esd->GetNumberOfTracks();
3203   for (Int_t itrack = 0; itrack < ntracks; itrack++)
3204     {
3205       AliESDtrack *track = esd->GetTrack(itrack);
3206       Int_t nsp = 0;
3207       Int_t idx[200];
3208       for (Int_t i=0; i<200; ++i) idx[i] = -1; //PH avoid uninitialized values
3209       for (Int_t iDet = 5; iDet >= 0; iDet--) {// TOF, TRD, TPC, ITS clusters
3210           nsp += (iDet==GetDetIndex("TRD")) ? track->GetTRDntracklets():track->GetNcls(iDet);
3211
3212           if (iDet==GetDetIndex("ITS")) { // ITS "extra" clusters
3213              track->GetClusters(iDet,idx);
3214              for (Int_t i=6; i<12; i++) if(idx[i] >= 0) nsp++;
3215           }  
3216       }
3217
3218       if (nsp) {
3219         AliTrackPointArray *sp = new AliTrackPointArray(nsp);
3220         track->SetTrackPointArray(sp);
3221         Int_t isptrack = 0;
3222         for (Int_t iDet = 5; iDet >= 0; iDet--) {
3223           AliTracker *tracker = fTracker[iDet];
3224           if (!tracker) continue;
3225           Int_t nspdet = (iDet==GetDetIndex("TRD")) ? track->GetTRDtracklets(idx):track->GetClusters(iDet,idx);
3226
3227           if (iDet==GetDetIndex("ITS")) // ITS "extra" clusters             
3228              for (Int_t i=6; i<12; i++) if(idx[i] >= 0) nspdet++;
3229
3230           if (nspdet <= 0) continue;
3231           AliTrackPoint p;
3232           Int_t isp = 0;
3233           Int_t isp2 = 0;
3234           while (isp2 < nspdet) {
3235             Bool_t isvalid=kTRUE;
3236
3237             Int_t index=idx[isp++];
3238             if (index < 0) continue;
3239
3240             TString dets = fgkDetectorName[iDet];
3241             if ((fUseTrackingErrorsForAlignment.CompareTo(dets) == 0) ||
3242             fUseTrackingErrorsForAlignment.BeginsWith(dets+" ") ||
3243             fUseTrackingErrorsForAlignment.EndsWith(" "+dets) ||
3244             fUseTrackingErrorsForAlignment.Contains(" "+dets+" ")) {
3245               isvalid = tracker->GetTrackPointTrackingError(index,p,track);
3246             } else {
3247               isvalid = tracker->GetTrackPoint(index,p); 
3248             } 
3249             isp2++;
3250             if (!isvalid) continue;
3251             if (iDet==GetDetIndex("ITS") && (isp-1)>=6) p.SetExtra();
3252             sp->AddPoint(isptrack,&p); isptrack++;
3253           }
3254         }       
3255       }
3256     }
3257 }
3258
3259 //_____________________________________________________________________________
3260 void AliReconstruction::FillRawDataErrorLog(Int_t iEvent, AliESDEvent* esd)
3261 {
3262   // The method reads the raw-data error log
3263   // accumulated within the rawReader.
3264   // It extracts the raw-data errors related to
3265   // the current event and stores them into
3266   // a TClonesArray inside the esd object.
3267
3268   if (!fRawReader) return;
3269
3270   for(Int_t i = 0; i < fRawReader->GetNumberOfErrorLogs(); i++) {
3271
3272     AliRawDataErrorLog *log = fRawReader->GetErrorLog(i);
3273     if (!log) continue;
3274     if (iEvent != log->GetEventNumber()) continue;
3275
3276     esd->AddRawDataErrorLog(log);
3277   }
3278
3279 }
3280
3281 //_____________________________________________________________________________
3282 // void AliReconstruction::CheckQA()
3283 // {
3284 // check the QA of SIM for this run and remove the detectors 
3285 // with status Fatal
3286   
3287 //      TString newRunLocalReconstruction ; 
3288 //      TString newRunTracking ;
3289 //      TString newFillESD ;
3290 //       
3291 //      for (Int_t iDet = 0; iDet < AliQAv1::kNDET; iDet++) {
3292 //              TString detName(AliQAv1::GetDetName(iDet)) ;
3293 //              AliQAv1 * qa = AliQAv1::Instance(AliQAv1::DETECTORINDEX_t(iDet)) ;       
3294 //      if ( qa->IsSet(AliQAv1::DETECTORINDEX_t(iDet), AliQAv1::kSIM, specie, AliQAv1::kFATAL)) {
3295 //        AliInfo(Form("QA status for %s %s in Hits and/or SDIGITS  and/or Digits was Fatal; No reconstruction performed", 
3296 //                   detName.Data(), AliRecoParam::GetEventSpecieName(es))) ;
3297 //                      } else {
3298 //                      if ( fRunLocalReconstruction.Contains(AliQAv1::GetDetName(iDet)) || 
3299 //                                      fRunLocalReconstruction.Contains("ALL") )  {
3300 //                              newRunLocalReconstruction += detName ; 
3301 //                              newRunLocalReconstruction += " " ;                      
3302 //                      }
3303 //                      if ( fRunTracking.Contains(AliQAv1::GetDetName(iDet)) || 
3304 //                                      fRunTracking.Contains("ALL") )  {
3305 //                              newRunTracking += detName ; 
3306 //                              newRunTracking += " " ;                         
3307 //                      }
3308 //                      if ( fFillESD.Contains(AliQAv1::GetDetName(iDet)) || 
3309 //                                      fFillESD.Contains("ALL") )  {
3310 //                              newFillESD += detName ; 
3311 //                              newFillESD += " " ;                     
3312 //                      }
3313 //              }
3314 //      }
3315 //      fRunLocalReconstruction = newRunLocalReconstruction ; 
3316 //      fRunTracking            = newRunTracking ; 
3317 //      fFillESD                = newFillESD ; 
3318 // }
3319
3320 //_____________________________________________________________________________
3321 Int_t AliReconstruction::GetDetIndex(const char* detector)
3322 {
3323   // return the detector index corresponding to detector
3324   Int_t index = -1 ; 
3325   for (index = 0; index < kNDetectors ; index++) {
3326     if ( strcmp(detector, fgkDetectorName[index]) == 0 )
3327         break ; 
3328   }     
3329   return index ; 
3330 }
3331 //_____________________________________________________________________________
3332 Bool_t AliReconstruction::FinishPlaneEff() {
3333  //
3334  // Here execute all the necessary operationis, at the end of the tracking phase,
3335  // in case that evaluation of PlaneEfficiencies was required for some detector.
3336  // E.g., write into a DataBase file the PlaneEfficiency which have been evaluated.
3337  //
3338  // This Preliminary version works only FOR ITS !!!!!
3339  // other detectors (TOF,TRD, etc. have to develop their specific codes)
3340  //
3341  //  Input: none
3342  //  Return: kTRUE if all operations have been done properly, kFALSE otherwise
3343  //
3344  Bool_t ret=kFALSE;
3345  TString detStr = fLoadCDB;
3346  //for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
3347  for (Int_t iDet = 0; iDet < 1; iDet++) { // for the time being only ITS
3348    if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
3349    if(fTracker[iDet] && fTracker[iDet]->GetPlaneEff()) {
3350       AliPlaneEff *planeeff=fTracker[iDet]->GetPlaneEff();
3351       TString name=planeeff->GetName();
3352       name+=".root";
3353       TFile* pefile = TFile::Open(name, "RECREATE");
3354       ret=(Bool_t)planeeff->Write();
3355       pefile->Close();
3356       if(planeeff->GetCreateHistos()) {
3357         TString hname=planeeff->GetName();
3358         hname+="Histo.root";
3359         ret*=planeeff->WriteHistosToFile(hname,"RECREATE");
3360       }
3361    }
3362    if(fSPDTrackleter) {
3363      AliPlaneEff *planeeff=fSPDTrackleter->GetPlaneEff();
3364       TString name="AliITSPlaneEffSPDtracklet.root";
3365       TFile* pefile = TFile::Open(name, "RECREATE");
3366       ret=(Bool_t)planeeff->Write();
3367       pefile->Close();
3368       AliESDEvent *dummy=NULL;
3369       ret=(Bool_t)fSPDTrackleter->PostProcess(dummy); // take care of writing other files
3370    }
3371  }
3372  return ret;
3373 }
3374 //_____________________________________________________________________________
3375 Bool_t AliReconstruction::InitPlaneEff() {
3376 //
3377  // Here execute all the necessary operations, before of the tracking phase,
3378  // for the evaluation of PlaneEfficiencies, in case required for some detectors.
3379  // E.g., read from a DataBase file a first evaluation of the PlaneEfficiency
3380  // which should be updated/recalculated.
3381  //
3382  // This Preliminary version will work only FOR ITS !!!!!
3383  // other detectors (TOF,TRD, etc. have to develop their specific codes)
3384  //
3385  //  Input: none
3386  //  Return: kTRUE if all operations have been done properly, kFALSE otherwise
3387  //
3388
3389   fSPDTrackleter = NULL;
3390   TString detStr = fLoadCDB;
3391   if (IsSelected(fgkDetectorName[0], detStr)) {
3392     AliReconstructor* itsReconstructor = GetReconstructor(0);
3393     if (itsReconstructor) {
3394       fSPDTrackleter = itsReconstructor->CreateTrackleter(); // this is NULL unless required in RecoParam
3395     }
3396     if (fSPDTrackleter) {
3397       AliInfo("Trackleter for SPD has been created");
3398     }
3399   }
3400  return kTRUE;
3401 }
3402
3403 //_____________________________________________________________________________
3404 Bool_t AliReconstruction::InitAliEVE()
3405 {
3406   // This method should be called only in case 
3407   // AliReconstruction is run
3408   // within the alieve environment.
3409   // It will initialize AliEVE in a way
3410   // so that it can visualize event processed
3411   // by AliReconstruction.
3412   // The return flag shows whenever the
3413   // AliEVE initialization was successful or not.
3414
3415   TString macroStr;
3416   macroStr.Form("%s/EVE/macros/alieve_online.C",gSystem->ExpandPathName("$ALICE_ROOT"));
3417   AliInfo(Form("Loading AliEVE macro: %s",macroStr.Data()));
3418   if (gROOT->LoadMacro(macroStr.Data()) != 0) return kFALSE;
3419
3420   gROOT->ProcessLine("if (!AliEveEventManager::GetMaster()){new AliEveEventManager();AliEveEventManager::GetMaster()->AddNewEventCommand(\"alieve_online_on_new_event()\");gEve->AddEvent(AliEveEventManager::GetMaster());};");
3421   gROOT->ProcessLine("alieve_online_init()");
3422
3423   return kTRUE;
3424 }
3425   
3426 //_____________________________________________________________________________
3427 void AliReconstruction::RunAliEVE()
3428 {
3429   // Runs AliEVE visualisation of
3430   // the current event.
3431   // Should be executed only after
3432   // successful initialization of AliEVE.
3433
3434   AliInfo("Running AliEVE...");
3435   gROOT->ProcessLine(Form("AliEveEventManager::GetMaster()->SetEvent((AliRunLoader*)0x%lx,(AliRawReader*)0x%lx,(AliESDEvent*)0x%lx,(AliESDfriend*)0x%lx);",fRunLoader,fRawReader,fesd,fesdf));
3436   gSystem->Run();
3437 }
3438
3439 //_____________________________________________________________________________
3440 Bool_t AliReconstruction::SetRunQA(TString detAndAction) 
3441 {
3442         // Allows to run QA for a selected set of detectors
3443         // and a selected set of tasks among RAWS, DIGITSR, RECPOINTS and ESDS
3444         // all selected detectors run the same selected tasks
3445         
3446         if (!detAndAction.Contains(":")) {
3447                 AliError( Form("%s is a wrong syntax, use \"DetectorList:ActionList\" \n", detAndAction.Data()) ) ;
3448                 fRunQA = kFALSE ;
3449                 return kFALSE ;                 
3450         }
3451         Int_t colon = detAndAction.Index(":") ; 
3452         fQADetectors = detAndAction(0, colon) ; 
3453         fQATasks   = detAndAction(colon+1, detAndAction.Sizeof() ) ; 
3454         if (fQATasks.Contains("ALL") ) {
3455                 fQATasks = Form("%d %d %d %d", AliQAv1::kRAWS, AliQAv1::kDIGITSR, AliQAv1::kRECPOINTS, AliQAv1::kESDS) ; 
3456         } else {
3457                 fQATasks.ToUpper() ; 
3458                 TString tempo("") ; 
3459                 if ( fQATasks.Contains("RAW") ) 
3460                         tempo = Form("%d ", AliQAv1::kRAWS) ; 
3461                 if ( fQATasks.Contains("DIGIT") ) 
3462                         tempo += Form("%d ", AliQAv1::kDIGITSR) ; 
3463                 if ( fQATasks.Contains("RECPOINT") ) 
3464                         tempo += Form("%d ", AliQAv1::kRECPOINTS) ; 
3465                 if ( fQATasks.Contains("ESD") ) 
3466                         tempo += Form("%d ", AliQAv1::kESDS) ; 
3467                 fQATasks = tempo ; 
3468                 if (fQATasks.IsNull()) {
3469                         AliInfo("No QA requested\n")  ;
3470                         fRunQA = kFALSE ;
3471                         return kTRUE ; 
3472                 }
3473         }       
3474         TString tempo(fQATasks) ; 
3475         tempo.ReplaceAll(Form("%d", AliQAv1::kRAWS), AliQAv1::GetTaskName(AliQAv1::kRAWS))      ;
3476         tempo.ReplaceAll(Form("%d", AliQAv1::kDIGITSR), AliQAv1::GetTaskName(AliQAv1::kDIGITSR)) ;      
3477         tempo.ReplaceAll(Form("%d", AliQAv1::kRECPOINTS), AliQAv1::GetTaskName(AliQAv1::kRECPOINTS)) ;  
3478         tempo.ReplaceAll(Form("%d", AliQAv1::kESDS), AliQAv1::GetTaskName(AliQAv1::kESDS)) ;    
3479         AliInfo( Form("QA will be done on \"%s\" for \"%s\"\n", fQADetectors.Data(), tempo.Data()) ) ;  
3480         fRunQA = kTRUE ;
3481         return kTRUE; 
3482
3483
3484 //_____________________________________________________________________________
3485 Bool_t AliReconstruction::InitRecoParams() 
3486 {
3487   // The method accesses OCDB and retrieves all
3488   // the available reco-param objects from there.
3489
3490   Bool_t isOK = kTRUE;
3491
3492   if (fRecoParam.GetDetRecoParamArray(kNDetectors)) {
3493     AliInfo("Using custom GRP reconstruction parameters");
3494   }
3495   else {
3496     AliInfo("Loading GRP reconstruction parameter objects");
3497
3498     AliCDBPath path("GRP","Calib","RecoParam");
3499     AliCDBEntry *entry=AliCDBManager::Instance()->Get(path.GetPath());
3500     if(!entry){ 
3501       AliWarning("Couldn't find GRP RecoParam entry in OCDB");
3502       isOK = kFALSE;
3503     }
3504     else {
3505       TObject *recoParamObj = entry->GetObject();
3506       if (dynamic_cast<TObjArray*>(recoParamObj)) {
3507         // GRP has a normal TobjArray of AliDetectorRecoParam objects
3508         // Registering them in AliRecoParam
3509         fRecoParam.AddDetRecoParamArray(kNDetectors,dynamic_cast<TObjArray*>(recoParamObj));
3510       }
3511       else if (dynamic_cast<AliDetectorRecoParam*>(recoParamObj)) {
3512         // GRP has only onse set of reco parameters
3513         // Registering it in AliRecoParam
3514         AliInfo("Single set of GRP reconstruction parameters found");
3515         dynamic_cast<AliDetectorRecoParam*>(recoParamObj)->SetAsDefault();
3516         fRecoParam.AddDetRecoParam(kNDetectors,dynamic_cast<AliDetectorRecoParam*>(recoParamObj));
3517       }
3518       else {
3519         AliError("No valid GRP RecoParam object found in the OCDB");
3520         isOK = kFALSE;
3521       }
3522       entry->SetOwner(0);
3523     }
3524   }
3525
3526   TString detStr = fLoadCDB;
3527   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
3528
3529     if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
3530
3531     if (fRecoParam.GetDetRecoParamArray(iDet)) {
3532       AliInfo(Form("Using custom reconstruction parameters for detector %s",fgkDetectorName[iDet]));
3533       continue;
3534     }
3535
3536     AliInfo(Form("Loading reconstruction parameter objects for detector %s",fgkDetectorName[iDet]));
3537   
3538     AliCDBPath path(fgkDetectorName[iDet],"Calib","RecoParam");
3539     AliCDBEntry *entry=AliCDBManager::Instance()->Get(path.GetPath());
3540     if(!entry){ 
3541       AliWarning(Form("Couldn't find RecoParam entry in OCDB for detector %s",fgkDetectorName[iDet]));
3542       isOK = kFALSE;
3543     }
3544     else {
3545       TObject *recoParamObj = entry->GetObject();
3546       if (dynamic_cast<TObjArray*>(recoParamObj)) {
3547         // The detector has a normal TobjArray of AliDetectorRecoParam objects
3548         // Registering them in AliRecoParam
3549         fRecoParam.AddDetRecoParamArray(iDet,dynamic_cast<TObjArray*>(recoParamObj));
3550       }
3551       else if (dynamic_cast<AliDetectorRecoParam*>(recoParamObj)) {
3552         // The detector has only onse set of reco parameters
3553         // Registering it in AliRecoParam
3554         AliInfo(Form("Single set of reconstruction parameters found for detector %s",fgkDetectorName[iDet]));
3555         dynamic_cast<AliDetectorRecoParam*>(recoParamObj)->SetAsDefault();
3556         fRecoParam.AddDetRecoParam(iDet,dynamic_cast<AliDetectorRecoParam*>(recoParamObj));
3557       }
3558       else {
3559         AliError(Form("No valid RecoParam object found in the OCDB for detector %s",fgkDetectorName[iDet]));
3560         isOK = kFALSE;
3561       }
3562       entry->SetOwner(0);
3563       //      FIX ME: We have to disable the unloading of reco-param CDB
3564       //      entries because QA framework is using them. Has to be fix in
3565       //      a way that the QA takes the objects already constructed in
3566       //      this method.
3567       //      AliCDBManager::Instance()->UnloadFromCache(path.GetPath());
3568     }
3569   }
3570
3571   if (AliDebugLevel() > 0) fRecoParam.Print();
3572
3573   return isOK;
3574 }
3575
3576 //_____________________________________________________________________________
3577 Bool_t AliReconstruction::GetEventInfo() 
3578 {
3579   // Fill the event info object
3580   // ...
3581   AliCodeTimerAuto("",0)
3582
3583   AliCentralTrigger *aCTP = NULL;
3584   if (fRawReader) {
3585     fEventInfo.SetEventType(fRawReader->GetType());
3586
3587     ULong64_t mask = fRawReader->GetClassMask();
3588     fEventInfo.SetTriggerMask(mask);
3589     UInt_t clmask = fRawReader->GetDetectorPattern()[0];
3590     fEventInfo.SetTriggerCluster(AliDAQ::ListOfTriggeredDetectors(clmask));
3591
3592     aCTP = new AliCentralTrigger();
3593     TString configstr("");
3594     if (!aCTP->LoadConfiguration(configstr)) { // Load CTP config from OCDB
3595       AliError("No trigger configuration found in OCDB! The trigger configuration information will not be used!");
3596       delete aCTP;
3597       return kFALSE;
3598     }
3599     aCTP->SetClassMask(mask);
3600     aCTP->SetClusterMask(clmask);
3601   }
3602   else {
3603     fEventInfo.SetEventType(AliRawEventHeaderBase::kPhysicsEvent);
3604
3605     if (fRunLoader && (!fRunLoader->LoadTrigger())) {
3606       aCTP = fRunLoader->GetTrigger();
3607       fEventInfo.SetTriggerMask(aCTP->GetClassMask());
3608       // get inputs from actp - just get
3609       AliESDHeader* esdheader = fesd->GetHeader();
3610       esdheader->SetL0TriggerInputs(aCTP->GetL0TriggerInputs());
3611       esdheader->SetL1TriggerInputs(aCTP->GetL1TriggerInputs());
3612       esdheader->SetL2TriggerInputs(aCTP->GetL2TriggerInputs());
3613       fEventInfo.SetTriggerCluster(AliDAQ::ListOfTriggeredDetectors(aCTP->GetClusterMask()));
3614     }
3615     else {
3616       AliWarning("No trigger can be loaded! The trigger information will not be used!");
3617       return kFALSE;
3618     }
3619   }
3620
3621   AliTriggerConfiguration *config = aCTP->GetConfiguration();
3622   if (!config) {
3623     AliError("No trigger configuration has been found! The trigger configuration information will not be used!");
3624     if (fRawReader) delete aCTP;
3625     return kFALSE;
3626   }
3627
3628   UChar_t clustmask = 0;
3629   TString trclasses;
3630   ULong64_t trmask = fEventInfo.GetTriggerMask();
3631   const TObjArray& classesArray = config->GetClasses();
3632   Int_t nclasses = classesArray.GetEntriesFast();
3633   for( Int_t iclass=0; iclass < nclasses; iclass++ ) {
3634     AliTriggerClass* trclass = (AliTriggerClass*)classesArray.At(iclass);
3635     if (trclass && trclass->GetMask()>0) {
3636       Int_t trindex = TMath::Nint(TMath::Log2(trclass->GetMask()));
3637       fesd->SetTriggerClass(trclass->GetName(),trindex);
3638       if (fRawReader) fRawReader->LoadTriggerClass(trclass->GetName(),trindex);
3639       if (trmask & (1ull << trindex)) {
3640         trclasses += " ";
3641         trclasses += trclass->GetName();
3642         trclasses += " ";
3643         clustmask |= trclass->GetCluster()->GetClusterMask();
3644       }
3645     }
3646   }
3647   fEventInfo.SetTriggerClasses(trclasses);
3648
3649   // Write names of active trigger inputs in ESD Header
3650   const TObjArray& inputsArray = config->GetInputs(); 
3651   Int_t ninputs = inputsArray.GetEntriesFast();
3652   for( Int_t iinput=0; iinput < ninputs; iinput++ ) {
3653     AliTriggerInput* trginput = (AliTriggerInput*)inputsArray.At(iinput);
3654     if (trginput && trginput->GetMask()>0) {
3655       Int_t inputIndex = (Int_t)TMath::Nint(TMath::Log2(trginput->GetMask()));
3656       AliESDHeader* headeresd = fesd->GetHeader();
3657       Int_t trglevel = (Int_t)trginput->GetLevel();
3658       if (trglevel == 0) headeresd->SetActiveTriggerInputs(trginput->GetInputName(), inputIndex);
3659       if (trglevel == 1) headeresd->SetActiveTriggerInputs(trginput->GetInputName(), inputIndex+24);
3660       if (trglevel == 2) headeresd->SetActiveTriggerInputs(trginput->GetInputName(), inputIndex+48);
3661     }
3662   }
3663
3664   // Set the information in ESD
3665   fesd->SetTriggerMask(trmask);
3666   fesd->SetTriggerCluster(clustmask);
3667
3668   if (!aCTP->CheckTriggeredDetectors()) {
3669     if (fRawReader) delete aCTP;
3670     return kFALSE;
3671   }    
3672
3673   if (fRawReader) delete aCTP;
3674
3675   // We have to fill also the HLT decision here!!
3676   // ...
3677
3678   return kTRUE;
3679 }
3680
3681 const char *AliReconstruction::MatchDetectorList(const char *detectorList, UInt_t detectorMask)
3682 {
3683   // Match the detector list found in the rec.C or the default 'ALL'
3684   // to the list found in the GRP (stored there by the shuttle PP which
3685   // gets the information from ECS)
3686   static TString resultList;
3687   TString detList = detectorList;
3688
3689   resultList = "";
3690
3691   for(Int_t iDet = 0; iDet < (AliDAQ::kNDetectors-1); iDet++) {
3692     if ((detectorMask >> iDet) & 0x1) {
3693       TString det = AliDAQ::OfflineModuleName(iDet);
3694       if ((detList.CompareTo("ALL") == 0) ||
3695           ((detList.BeginsWith("ALL ") ||
3696             detList.EndsWith(" ALL") ||
3697             detList.Contains(" ALL ")) &&
3698            !(detList.BeginsWith("-"+det+" ") ||
3699              detList.EndsWith(" -"+det) ||
3700              detList.Contains(" -"+det+" "))) ||
3701           (detList.CompareTo(det) == 0) ||
3702           detList.BeginsWith(det+" ") ||
3703           detList.EndsWith(" "+det) ||
3704           detList.Contains( " "+det+" " )) {
3705         if (!resultList.EndsWith(det + " ")) {
3706           resultList += det;
3707           resultList += " ";
3708         }
3709       }        
3710     }
3711   }
3712
3713   // HLT
3714   if ((detectorMask >> AliDAQ::kHLTId) & 0x1) {
3715     TString hltDet = AliDAQ::OfflineModuleName(AliDAQ::kNDetectors-1);
3716     if ((detList.CompareTo("ALL") == 0) ||
3717         ((detList.BeginsWith("ALL ") ||
3718           detList.EndsWith(" ALL") ||
3719           detList.Contains(" ALL ")) &&
3720          !(detList.BeginsWith("-"+hltDet+" ") ||
3721            detList.EndsWith(" -"+hltDet) ||
3722            detList.Contains(" -"+hltDet+" "))) ||
3723         (detList.CompareTo(hltDet) == 0) ||
3724         detList.BeginsWith(hltDet+" ") ||
3725         detList.EndsWith(" "+hltDet) ||
3726         detList.Contains( " "+hltDet+" " )) {
3727       resultList += hltDet;
3728     }
3729   }
3730
3731   return resultList.Data();
3732
3733 }
3734
3735 //______________________________________________________________________________
3736 void AliReconstruction::Abort(const char *method, EAbort what)
3737 {
3738   // Abort processing. If what = kAbortProcess, the Process() loop will be
3739   // aborted. If what = kAbortFile, the current file in a chain will be
3740   // aborted and the processing will continue with the next file, if there
3741   // is no next file then Process() will be aborted. Abort() can also  be
3742   // called from Begin(), SlaveBegin(), Init() and Notify(). After abort
3743   // the SlaveTerminate() and Terminate() are always called. The abort flag
3744   // can be checked in these methods using GetAbort().
3745   //
3746   // The method is overwritten in AliReconstruction for better handling of
3747   // reco specific errors 
3748
3749   if (!fStopOnError) return;
3750
3751   CleanUp();
3752
3753   TString whyMess = method;
3754   whyMess += " failed! Aborting...";
3755
3756   AliError(whyMess.Data());
3757
3758   fAbort = what;
3759   TString mess = "Abort";
3760   if (fAbort == kAbortProcess)
3761     mess = "AbortProcess";
3762   else if (fAbort == kAbortFile)
3763     mess = "AbortFile";
3764
3765   Info(mess, whyMess.Data());
3766 }
3767
3768 //______________________________________________________________________________
3769 Bool_t AliReconstruction::ProcessEvent(void* event)
3770 {
3771   // Method that is used in case the event loop
3772   // is steered from outside, for example by AMORE
3773   // 'event' is a pointer to the DATE event in the memory
3774
3775   if (fRawReader) delete fRawReader;
3776   fRawReader = new AliRawReaderDate(event);
3777   fStatus = ProcessEvent(fRunLoader->GetNumberOfEvents());  
3778   delete fRawReader;
3779   fRawReader = NULL;
3780
3781   return fStatus;
3782 }
3783
3784 //______________________________________________________________________________
3785 Bool_t AliReconstruction::ParseOutput()
3786 {
3787   // The method parses the output file
3788   // location string in order to steer
3789   // properly the selector
3790
3791   TPMERegexp re1("(\\w+\\.zip#\\w+\\.root):([,*\\w+\\.root,*]+)@dataset://(\\w++)");
3792   TPMERegexp re2("(\\w+\\.root)?@?dataset://(\\w++)");
3793
3794   if (re1.Match(fESDOutput) == 4) {
3795     // root archive with output files stored and regustered
3796     // in proof dataset
3797     gProof->AddInput(new TNamed("PROOF_OUTPUTFILE",re1[1].Data()));
3798     gProof->AddInput(new TNamed("PROOF_OUTPUTFILE_LOCATION",re1[3].Data()));
3799     gProof->AddInput(new TNamed("PROOF_OUTPUTFILE_DATASET",""));
3800     gProof->AddInput(new TNamed("PROOF_OUTPUTFILE_ARCHIVE",re1[2].Data()));
3801     AliInfo(Form("%s files will be stored within %s in dataset %s",
3802                  re1[2].Data(),
3803                  re1[1].Data(),
3804                  re1[3].Data()));
3805   }
3806   else if (re2.Match(fESDOutput) == 3) {
3807     // output file stored and registered
3808     // in proof dataset
3809     gProof->AddInput(new TNamed("PROOF_OUTPUTFILE",(re2[1].IsNull()) ? "AliESDs.root" : re2[1].Data()));
3810     gProof->AddInput(new TNamed("PROOF_OUTPUTFILE_LOCATION",re2[2].Data()));
3811     gProof->AddInput(new TNamed("PROOF_OUTPUTFILE_DATASET",""));
3812     AliInfo(Form("%s will be stored in dataset %s",
3813                  (re2[1].IsNull()) ? "AliESDs.root" : re2[1].Data(),
3814                  re2[2].Data()));
3815   }
3816   else {
3817     if (fESDOutput.IsNull()) {
3818       // Output location not given.
3819       // Assuming xrootd has been already started and
3820       // the output file has to be sent back
3821       // to the client machine
3822       TString esdUrl(Form("root://%s/%s/",
3823                           TUrl(gSystem->HostName()).GetHostFQDN(),
3824                           gSystem->pwd()));
3825       gProof->AddInput(new TNamed("PROOF_OUTPUTFILE","AliESDs.root"));
3826       gProof->AddInput(new TNamed("PROOF_OUTPUTFILE_LOCATION",esdUrl.Data()));
3827       AliInfo(Form("AliESDs.root will be stored in %s",
3828                    esdUrl.Data()));
3829     }
3830     else {
3831       // User specified an output location.
3832       // Ones has just to parse it here
3833       TUrl outputUrl(fESDOutput.Data());
3834       TString outputFile(gSystem->BaseName(outputUrl.GetFile()));
3835       gProof->AddInput(new TNamed("PROOF_OUTPUTFILE",outputFile.IsNull() ? "AliESDs.root" : outputFile.Data()));
3836       TString outputLocation(outputUrl.GetUrl());
3837       outputLocation.ReplaceAll(outputFile.Data(),"");
3838       gProof->AddInput(new TNamed("PROOF_OUTPUTFILE_LOCATION",outputLocation.Data()));
3839       AliInfo(Form("%s will be stored in %s",
3840                    outputFile.IsNull() ? "AliESDs.root" : outputFile.Data(),
3841                    outputLocation.Data()));
3842     }
3843   }
3844
3845   return kTRUE;
3846 }