]> git.uio.no Git - u/mrichter/AliRoot.git/blob - PWG2/FORWARD/analysis2/TrainSetup.C
693e16b6ac09973152ac8178122d77a5baeded21
[u/mrichter/AliRoot.git] / PWG2 / FORWARD / analysis2 / TrainSetup.C
1 /**
2  * @file   TrainSetup.C
3  * @author Christian Holm Christensen <cholm@dalsgaard.hehi.nbi.dk>
4  * @date   Wed Mar 23 12:12:00 2011
5  * 
6  * @brief  
7  * 
8  * @ingroup pwg2_forward_scripts_makers
9  * 
10  */
11
12 #ifndef __CINT__
13 #include <fstream>
14
15 #include <TAlienCollection.h>
16 #include <TArrayI.h>
17 #include <TChain.h>
18 #include <TDatime.h>
19 #include <TEnv.h>
20 #include <TFile.h>
21 #include <TGrid.h>
22 #include <TList.h>
23 #include <TObjString.h>
24 #include <TProof.h>
25 #include <TString.h>
26 #include <TSystem.h>
27 #include <TSystemDirectory.h>
28 #include <TSystemFile.h>
29 #include <TROOT.h>
30
31 #include <AliAODHandler.h>
32 #include <AliAODInputHandler.h>
33 #include <AliAnalysisDataContainer.h>
34 #include <AliAnalysisManager.h>
35 #include <AliAnalysisAlien.h>
36 #include <AliESDInputHandler.h>
37 #include <AliMCEventHandler.h>
38 #include <AliVEventHandler.h>
39 #include <AliPhysicsSelection.h>
40 #else
41 class TArrayI;
42 class TChain;
43 class AliAnalysisManager;
44 #endif
45
46 //====================================================================
47 /** 
48  * Generic set-up of an analysis train using the grid-handler (AliEn plugin). 
49  * 
50  * Users should define a class that derives from this.  The class
51  * should implement the member function CreateTasks to add needed
52  * tasks to the train
53  * 
54  * @code 
55  * // MyTrain.C 
56  * class MyTrain : public TrainSetup
57  * {
58  * public:
59  *   MyTrain(Bool_t   dateTime = false, 
60  *           UShort_t year     = 0, 
61  *           UShort_t month    = 0, 
62  *           UShort_t day      = 0, 
63  *           UShort_t hour     = 0, 
64  *           UShort_t min      = 0) 
65  *     : TrainSetup("My train", dateTime, year, month, day, hour, min)
66  *   {}
67  *   void Run(const char* type, const char* mode, const char* oper, 
68  *            Int_t nEvents=-1, Bool_t mc=false,
69  *            Bool_t usePar=false)
70  *   {
71  *     Exec(type, mode, oper, nEvents, mc, usePar);
72  *   }
73  * protected:
74  *   void CreateTasks(EMode mode, Bool_t par, AliAnalysisManager* mgr)
75  *   {
76  *     AliAnalysisManager::SetCommonFileName("my_analysis.root");
77  *     LoadLibrary("MyAnalysis", mode, par, true);
78  *     Bool_t mc = mgr->GetMCtruthEventHandler() != 0;
79  *     gROOT->Macro("MyAnalysis.C");
80  *   }
81  * };
82  * @endcode 
83  * 
84  * This can then be run like 
85  * 
86  * @verbatim 
87  * > aliroot 
88  * Root> .L TrainSetup.C 
89  * Root> .L MyTrain.C 
90  * Root> MyTrain t;
91  * Root> t.Run();
92  * @endverbatim 
93  * 
94  * or as a script 
95  * 
96  * @code 
97  * {
98  *   gROOT->LoadMacro("TrainSetup.C");
99  *   gROOT->LoadMacro("MyTrain.C");
100  *   MyTrain t;
101  *   t.Run();
102  * }
103  * @endcode 
104  * 
105  * To byte compile this, you need to 
106  * - load the ROOT AliEn library
107  * - load the analysis libraries 
108  * - add $ALICE_ROOT/include to header search 
109  * first 
110  *
111  * @verbatim 
112  * > aliroot 
113  * Root> gROOT->SetMacroPath(Form("%s:$(ALICE_ROOT)/PWG2/FORWARD/analysis2:"
114  * Root>                          "$ALICE_ROOT/ANALYSIS/macros",
115  * Root>                          gROOT->GetMacroPath()));
116  * Root> gSystem->AddIncludePath("-I${ALICE_ROOT}/include");
117  * Root> gSystem->Load("libRAliEn");
118  * Root> gSystem->Load("libANALYSIS");
119  * Root> gSystem->Load("libANALYSISalice");
120  * Root> gROOT->LoadMacro("TrainSetup.C+");
121  * @endverbatim 
122  * 
123  * @ingroup pwg2_forward_scripts_makers
124  * 
125  */
126 struct TrainSetup
127 {
128   /** 
129    * Data type to process 
130    */
131   enum EType { 
132     /** Event Summary Data */
133     kESD, 
134     /** Analysis Object Data */
135     kAOD
136   };
137   /**
138    * How to run the analysis
139    * 
140    */
141   enum EMode {
142     /** Locally */ 
143     kLocal = 1, 
144     /** In PROOF(-Lite) cluster */
145     kProof, 
146     /** On the Grid */
147     kGrid 
148   };
149   /**
150    * What stage of the analysis to run 
151    * 
152    */
153   enum EOper { 
154     /** Testing.  Local processing, a single copied from Grid */
155     kTest, 
156     /** Off-line */
157     kOffline, 
158     /** Submit to queue */
159     kSubmit, 
160     /** Merge and terminate */
161     kTerminate, 
162     /** Full run */
163     kFull
164   };
165
166   //__________________________________________________________________
167   /** 
168    * Constructor 
169    * 
170    * @param name         Name of analysis (free-form)
171    * @param useDateTime  Whether to append date and time to the name 
172    * @param year         Year - if not specified, taken from current date
173    * @param month        Month - if not specified, taken from current date 
174    * @param day          Day - if not specified, taken from current date 
175    * @param hour         Hour - if not specified, taken from current time  
176    * @param min          Minute - if not specified, taken from current time  
177    */
178   TrainSetup(const char* name, Bool_t useDateTime=true, 
179              UShort_t year=0, UShort_t month=0, 
180              UShort_t day=0, UShort_t hour=0, UShort_t min=0) 
181     : fName(name),
182       fRootVersion("v5-28-00a"),
183       fAliRootVersion("v4-21-18-AN"),
184       fProofServer("alicecaf.cern.ch"),
185       fDataDir("/alice/data/2010/LHC10c"),
186       fDataSet("/COMMON/COMMON/LHC09a4_run8100X#/esdTree"),
187       fXML(""), 
188       fRunNumbers(0),
189       fListOfPARs(),
190       fListOfSources(),
191       fListOfLibraries(),
192       fListOfExtras(),
193       fNReplica(4),
194       fESDPass(3),
195       fEscapedName(name),
196       fAllowOverwrite(kFALSE)
197   {
198     char  c[] = { ' ', '/', '@', 0 };
199     char* p   = c;
200     while (*p) { 
201       fEscapedName.ReplaceAll(Form("%c", *p), "_");
202       p++;
203     }
204
205     if (useDateTime) { 
206       if (year == 0 || month == 0 || day == 0) {
207         TDatime now;
208         year  = now.GetYear();
209         month = now.GetMonth();
210         day   = now.GetDay();
211         hour  = now.GetHour();
212         min   = now.GetMinute();
213       }
214       fEscapedName.Append(Form("_%04d%02d%02d_%02d%02d", 
215                                year, month, day, hour, min));
216     }
217
218   }
219
220   //__________________________________________________________________
221   /** 
222    * Parse a string into a type enum
223    * 
224    * @param type String to pass
225    * @param mc   True on return if the string contained "MC"
226    * 
227    * @return Enumaration value 
228    */
229   static EType ParseType(const char* type, Bool_t& mc)
230   {
231     mc = false;
232     TString sType(type);
233     sType.ToUpper();
234     EType eType = kESD;
235     if      (sType.Contains("MC"))    mc    = true;
236     if      (sType.Contains("ESD"))   eType = kESD; 
237     else if (sType.Contains("AOD"))   eType = kAOD;
238     else 
239       Fatal("Run", "Unknown type '%s'", type);
240     
241     return eType;
242   }
243   //__________________________________________________________________
244   /** 
245    * Return a string that reflects the passed mode
246    * 
247    * @param eMode Mode 
248    * 
249    * @return String representation of mode 
250    */
251   static const char* ModeString(EMode eMode) 
252   {
253     switch (eMode) {
254     case kLocal:        return "LOCAL";
255     case kProof:        return "PROOF";
256     case kGrid:         return "GRID";
257     }
258     return 0;
259   }
260   //__________________________________________________________________
261   /** 
262    * Parse a string for mode specifier 
263    * 
264    * @param mode Mode string
265    * 
266    * @return EMode value
267    */
268   static EMode ParseMode(const char* mode)
269   {
270     TString sMode(mode);
271     sMode.ToUpper();
272     EMode eMode = kLocal;
273     if      (sMode == "LOCAL") eMode = kLocal;
274     else if (sMode == "PROOF") eMode = kProof;
275     else if (sMode == "GRID")  eMode = kGrid;
276     else 
277       Fatal("Run", "Unknown mode '%s'", mode);
278     return eMode;
279   }
280
281   //__________________________________________________________________
282   /** 
283    * Return a string that reflects the passed operation
284    * 
285    * @param eOper Operation
286    * 
287    * @return String representation of operation 
288    */
289   static const char* OperString(EOper eOper) 
290   {
291     switch (eOper) {
292     case kTest:         return "TEST";
293     case kOffline:      return "OFFLINE";
294     case kSubmit:       return "SUBMIT";
295     case kTerminate:    return "TERMINATE";
296     case kFull:         return "FULL";
297     }
298     return 0;
299   }
300   //__________________________________________________________________
301   /** 
302    * Parse an operation string 
303    * 
304    * @param oper Operation 
305    * 
306    * @return An EOper value
307    */
308   static EOper ParseOperation(const char* oper)
309   {
310     TString sOper(oper);
311     sOper.ToUpper();
312     EOper eOper = kFull;
313     if      (sOper == "TEST")      eOper = kTest;
314     else if (sOper == "OFFLINE")   eOper = kOffline;
315     else if (sOper == "SUBMIT")    eOper = kSubmit;
316     else if (sOper == "TERMINATE") eOper = kTerminate;
317     else if (sOper == "FULL")      eOper = kFull;
318     else 
319       Fatal("Run", "unknown operation '%s'", oper);
320     return eOper;
321   }
322
323   //__________________________________________________________________
324   /** 
325    * Set ROOT version to use 
326    * 
327    * @param v 
328    */
329   void SetROOTVersion(const char* v)    { fRootVersion = v; }
330   //__________________________________________________________________
331   /** 
332    * Set AliROOT version to use 
333    * 
334    * @param v 
335    */
336   void SetAliROOTVersion(const char* v) { fAliRootVersion = v; }
337   //__________________________________________________________________
338   /** 
339    * Set the proof server URL
340    * 
341    * @param s 
342    */
343   void SetProofServer(const char* s)    { fProofServer = s; }
344   //__________________________________________________________________
345   /** 
346    * Set the GRID/Local data dir 
347    * 
348    * @param d 
349    */
350   void SetDataDir(const char* d)        { fDataDir = d; }
351   //__________________________________________________________________
352   /** 
353    * Set the PROOF data set 
354    * 
355    * @param d 
356    */
357   void SetDataSet(const char* d)        { fDataSet = d; }
358   //__________________________________________________________________
359   /** 
360    * Set the XML file to use 
361    * 
362    * @param x 
363    */
364   void SetXML(const char* x)            { fXML = x; }
365   //__________________________________________________________________
366   /** 
367    * Set how many replicas of the output we want 
368    * 
369    * @param n 
370    */
371   void SetNReplica(Int_t n)             { fNReplica = n; }
372   //__________________________________________________________________
373   /** 
374    * Add a source file to be copied and byte compiled on slaves 
375    * 
376    * @param src          Sources 
377    * @param addToExtra   If false, do not copy 
378    */
379   void AddSource(const char* src, bool addToExtra=true) 
380   { 
381     fListOfSources.Add(new TObjString(src)); 
382     if (addToExtra) AddExtraFile(src); // Source code isn't copied!
383   }
384   //__________________________________________________________________
385   /** 
386    * Add binary data to be uploaded to slaves 
387    * 
388    * @param lib Name of binary file 
389    */
390   void AddLibrary(const char* lib) { fListOfLibraries.Add(new TObjString(lib));}
391   //__________________________________________________________________
392   /** 
393    * Add a run to be analysed
394    *  
395    * @param run Run number
396    */
397   void AddRun(Int_t run) 
398   {
399     Int_t i = fRunNumbers.fN; fRunNumbers.Set(i+1); fRunNumbers[i] = run;
400   }
401   //__________________________________________________________________
402   /** 
403    * Read run numbers from a file 
404    * 
405    * @param filename File name 
406    */
407   void ReadRunNumbers(const char* filename)
408   {
409     std::ifstream file(filename);
410     if (!file) 
411       Fatal("ReadRunNumbers", "Cannot read from %s", filename);
412     
413     while (!file.eof()) { 
414       Int_t run;
415       file >> run;
416       AddRun(run);
417       Char_t c;
418       file >> c;
419       if (file.bad()) break;
420     }
421     file.close();
422   }
423   //__________________________________________________________________
424   /** 
425    * Add an extra file to be uploaded to slave 
426    * 
427    * @param file Extra file to be uploaded 
428    */
429   void AddExtraFile(const char* file)
430   {
431     if (!file || file[0] == '\0') return;
432     fListOfExtras.Add(new TObjString(file));
433   }
434   //__________________________________________________________________
435   /** 
436    * Set whether to allow overwritting existing files/directories 
437    * 
438    * @param allow If true, allow overwritting files/directories
439    */
440   void SetAllowOverwrite(Bool_t allow) { fAllowOverwrite = allow; }
441   //__________________________________________________________________
442   /** 
443    * Print the setup 
444    * 
445    */
446   void Print() const 
447   {
448     std::cout << fName << " train setup\n"
449               << "  ROOT version:         " << fRootVersion    << "\n"
450               << "  AliROOT version:      " << fAliRootVersion << "\n"
451               << "  Name of proof server: " << fProofServer    << "\n"
452               << "  Grid Input directory: " << fDataDir        << "\n"
453               << "  Proof data set name:  " << fDataSet        << "\n"
454               << "  XML collection:       " << fXML            << "\n"
455               << "  Storage replication:  " << fNReplica       << "\n"
456               << "  Run numbers:          " << std::flush;
457     for (Int_t i = 0; i < fRunNumbers.GetSize(); i++) 
458       std::cout << (i == 0 ? "" : ", ") << fRunNumbers.At(i);
459
460     std::cout << "\n"
461               << "  PAR files:            " << std::flush;
462     Bool_t first = true;
463     TObject* obj = 0;
464     TIter nextPar(&fListOfPARs);
465     while ((obj = nextPar())) {
466       std::cout << (first ? "" : ", ") << obj->GetName();
467       first = false;
468     }
469
470     std::cout << "\n"
471               << "  Script sources:       " << std::flush;
472     first = true;
473     TIter nextSrc(&fListOfSources);
474     while ((obj = nextSrc())) {
475       std::cout << (first ? "" : ", ") << obj->GetName();
476       first = false;
477     }
478
479     std::cout << "\n"
480               << "  Libraries to load:    " << std::flush;
481     first = true;
482     TIter nextLib(&fListOfLibraries);
483     while ((obj = nextLib())) {
484       std::cout << (first ? "" : ", ") << obj->GetName();
485       first = false;
486     }
487     std::cout << std::endl;
488
489     AliAnalysisGrid* plugin = 
490       AliAnalysisManager::GetAnalysisManager()->GetGridHandler();
491     if (!plugin) return;
492     
493   }
494
495 protected:
496   //__________________________________________________________________
497   TrainSetup(const TrainSetup& o)
498     : fName(o.fName),
499       fRootVersion(o.fRootVersion),
500       fAliRootVersion(o.fAliRootVersion),
501       fProofServer(o.fProofServer),
502       fDataDir(o.fDataDir),     
503       fDataSet(o.fDataSet),     
504       fXML(o.fXML),     
505       fRunNumbers(o.fRunNumbers),
506       fListOfPARs(),
507       fListOfSources(),
508       fListOfLibraries(),
509       fListOfExtras(),
510       fNReplica(o.fNReplica),
511       fESDPass(o.fESDPass)
512   {
513     TObject* obj = 0;
514     TIter nextPar(&o.fListOfPARs);
515     while ((obj = nextPar())) fListOfPARs.Add(obj->Clone());
516     TIter nextSrc(&o.fListOfSources);
517     while ((obj = nextSrc())) fListOfSources.Add(obj->Clone());
518     TIter nextLib(&o.fListOfLibraries);
519     while ((obj = nextLib())) fListOfLibraries.Add(obj->Clone());
520     TIter nextExa(&o.fListOfExtras);
521     while ((obj = nextExa())) fListOfExtras.Add(obj->Clone());
522   }
523   //__________________________________________________________________
524   TrainSetup& operator=(const TrainSetup& o)
525   {
526     fName               = o.fName;
527     fRootVersion        = o.fRootVersion;
528     fAliRootVersion     = o.fAliRootVersion;
529     fProofServer        = o.fProofServer;
530     fDataDir            = o.fDataDir;   
531     fDataSet            = o.fDataSet;   
532     fXML                = o.fXML;       
533     fNReplica           = o.fNReplica;  
534     fESDPass            = o.fESDPass;
535     fRunNumbers         = o.fRunNumbers;
536     TObject* obj = 0;
537     TIter nextPar(&o.fListOfPARs);
538     while ((obj = nextPar())) fListOfPARs.Add(obj->Clone());
539     TIter nextSrc(&o.fListOfSources);
540     while ((obj = nextSrc())) fListOfSources.Add(obj->Clone());
541     TIter nextLib(&o.fListOfLibraries);
542     while ((obj = nextLib())) fListOfLibraries.Add(obj->Clone());
543     TIter nextExa(&o.fListOfExtras);
544     while ((obj = nextExa())) fListOfExtras.Add(obj->Clone());
545
546     return *this;
547   }
548
549   //__________________________________________________________________
550   /** 
551    * Run this analysis 
552    * 
553    * @param type    Type of input for analysis  (kESD, kAOD)
554    * @param mode    Mode of job (kLocal, kProof, kGrid)
555    * @param oper    Operation 
556    * @param nEvents Number of events to analyse (<0 means all)
557    * @param mc      Whether to connect MC data 
558    * @param usePar  Whether to use PARs  
559    * @param dbg     Debug level
560    */
561   void Exec(const char*  type, 
562             const char*  mode="GRID", 
563             const char*  oper="FULL", 
564             Int_t        nEvents=-1, 
565             Bool_t       mc=false, 
566             Bool_t       usePar=false, 
567             Int_t        dbg=0)
568   {
569     EType eType = ParseType(type, mc);
570     EMode eMode = ParseMode(mode);
571     EOper eOper = ParseOperation(oper);
572
573     Exec(eType, eMode, eOper, nEvents, mc, usePar, dbg);
574   }
575
576   //__________________________________________________________________
577   /** 
578    * Run this analysis 
579    * 
580    * @param type    Type of input for analysis  (kESD, kAOD)
581    * @param mode    Mode of job (kLocal, kProof, kGrid)
582    * @param oper    Operation 
583    * @param nEvents Number of events to analyse (<0 means all)
584    * @param mc      Whether to connect MC data 
585    * @param usePar  Whether to use PARs  
586    * @param dbg     Debug level
587    */
588   void Exec(EType  type, 
589             EMode  mode, 
590             EOper  oper, 
591             Int_t  nEvents, 
592             Bool_t mc, 
593             Bool_t usePar, 
594             Int_t  dbg=0)
595   {
596     if (mode == kProof) usePar    = true;
597
598     if (!Connect(mode)) return;
599
600     TString cwd = gSystem->WorkingDirectory();
601     TString nam = EscapedName();
602     if (oper != kTerminate) { 
603       if (!fAllowOverwrite && !gSystem->AccessPathName(nam.Data())) {
604         Error("Exec", "File/directory %s already exists", nam.Data());
605         return;
606       }
607       if (gSystem->AccessPathName(nam.Data())) {
608         if (gSystem->MakeDirectory(nam.Data())) {
609           Error("Exec", "Failed to make directory %s", nam.Data());
610           return;
611         }
612       }
613     }
614     else {
615       if (gSystem->AccessPathName(nam.Data())) {
616         Error("Exec", "File/directory %s does not exists", nam.Data());
617         return;
618       }
619     }
620       
621     if (!gSystem->ChangeDirectory(nam.Data())) { 
622       Error("Exec", "Failed to change directory to %s", nam.Data());
623       return;
624     }
625     Info("Exec", "Made subdirectory %s, and cd'ed there", nam.Data());
626       
627     if (!LoadCommonLibraries(mode, usePar)) return;
628     
629     // --- Create analysis manager -----------------------------------
630     AliAnalysisManager *mgr  = new AliAnalysisManager(fName,"Analysis Train");
631
632     // In test mode, collect system information on every event 
633     // if (oper == kTest)  mgr->SetNSysInfo(1); 
634     if (dbg  >  0)      mgr->SetDebugLevel(dbg);
635     if (mode == kLocal) mgr->SetUseProgressBar(kTRUE, 100);
636    
637     // --- ESD input handler ------------------------------------------
638     AliVEventHandler*  inputHandler = CreateInputHandler(type);
639     if (inputHandler) mgr->SetInputEventHandler(inputHandler);
640     
641     // --- Monte-Carlo ------------------------------------------------
642     AliVEventHandler*  mcHandler = CreateMCHandler(type,mc);
643     if (mcHandler) mgr->SetMCtruthEventHandler(mcHandler);
644     
645     // --- AOD output handler -----------------------------------------
646     AliVEventHandler*  outputHandler = CreateOutputHandler(type);
647     if (outputHandler) mgr->SetOutputEventHandler(outputHandler);
648     
649     // --- Include analysis macro path in search path ----------------
650     gROOT->SetMacroPath(Form("%s:$ALICE_ROOT/ANALYSIS/macros",
651                              gROOT->GetMacroPath()));
652
653     // --- Physics selction ------------------------------------------
654     CreatePhysicsSelection(mc, mgr);
655     
656     // --- Create tasks ----------------------------------------------
657     CreateTasks(mode, usePar, mgr);
658
659     // --- Create Grid handler ----------------------------------------
660     // _must_ be done after all tasks has been added
661     AliAnalysisAlien* gridHandler = CreateGridHandler(type, mode, oper);
662     if (gridHandler) mgr->SetGridHandler(gridHandler);
663     
664     // --- Create the chain ------------------------------------------
665     TChain* chain = CreateChain(type, mode, oper);
666
667     // --- Print setup -----------------------------------------------
668     Print();
669
670     // --- Initialise the train --------------------------------------
671     if (!mgr->InitAnalysis())  {
672       gSystem->ChangeDirectory(cwd.Data());
673       Fatal("Run","Failed to initialise train");
674     }
675
676     // --- Show status -----------------------------------------------
677     mgr->PrintStatus();
678
679     Long64_t ret = StartAnalysis(mgr, mode, chain, nEvents);
680
681     // Make sure we go back 
682     gSystem->ChangeDirectory(cwd.Data());
683
684     if (ret < 0) Fatal("Exec", "Analysis failed");
685   }
686   //__________________________________________________________________
687   /** 
688    * Start the analysis 
689    * 
690    * @param mgr       Analysis manager
691    * @param mode      Run mode
692    * @param chain     Input data (local and proof only)
693    * @param nEvents   Number of events to analyse 
694    */
695   Long64_t StartAnalysis(AliAnalysisManager* mgr, 
696                          EMode               mode, 
697                          TChain*             chain,
698                          Int_t               nEvents)
699   {
700     // --- Run the analysis ------------------------------------------
701     switch (mode) { 
702     case kLocal: 
703       if (!chain) {
704         Error("StartAnalysis", "No chain defined");
705         return -1;
706       }
707       if (nEvents < 0) nEvents = chain->GetEntries();
708       return mgr->StartAnalysis(ModeString(mode), chain, nEvents);
709     case kProof: 
710       if (fDataSet.IsNull()) {
711         if (!chain) { 
712           Error("StartAnalysis", "No chain defined");
713           return -1;
714         }
715         if (nEvents < 0) nEvents = chain->GetEntries();
716         return mgr->StartAnalysis(ModeString(mode), chain, nEvents);
717       }
718       return mgr->StartAnalysis(ModeString(mode), fDataSet);
719     case kGrid: 
720       if (nEvents < 0)
721         return mgr->StartAnalysis(ModeString(mode));
722       return mgr->StartAnalysis(ModeString(mode), nEvents);
723     }
724     // We should never get  here 
725     return -1;
726   }
727   //__________________________________________________________________
728   /** 
729    * Return the escaped name 
730    * 
731    * 
732    * @return Escaped name 
733    */
734   const TString& EscapedName() const 
735   {
736     return fEscapedName;
737   }
738   //__________________________________________________________________
739   /** 
740    * Create a grid handler 
741    * 
742    * @param type Data type
743    * @param mode Run mode 
744    * @param oper Operation 
745    * 
746    * @return Grid handler 
747    */
748   virtual AliAnalysisAlien* CreateGridHandler(EType type, EMode mode, EOper oper)
749   {
750     if (mode != kGrid) return 0;
751
752     TString name = EscapedName();
753
754     // Create the plug-in object, and set run mode 
755     AliAnalysisAlien* plugin = new AliAnalysisAlien();
756     plugin->SetRunMode(OperString(oper));
757     
758     // Production mode - not used here 
759     // plugin->SetProductionMode();
760     
761     // Set output to be per run 
762     plugin->SetOutputToRunNo();
763
764     // Set the job tag 
765     plugin->SetJobTag(fName);
766
767     // Set number of test files - used in test mode only 
768     plugin->SetNtestFiles(1);
769     
770     // Set required version of software 
771     plugin->SetAPIVersion("V1.1x");
772     plugin->SetROOTVersion(fRootVersion);
773     plugin->SetAliROOTVersion(fAliRootVersion);
774
775     // Keep log files 
776     plugin->SetKeepLogs();
777
778     // Declare root of input data directory 
779     plugin->SetGridDataDir(fDataDir);
780
781     // Data search patterns 
782     if (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler())
783       plugin->SetRunPrefix("");
784     else
785       plugin->SetRunPrefix("000");
786     plugin->SetDataPattern(Form("*ESDs/pass%d/*/*%s.root", 
787                                 fESDPass, type == kESD ? "ESDs" : "AOD"));
788
789     // Add the run numbers 
790     for (Int_t i = 0; i < fRunNumbers.fN; i++) {
791       if (fRunNumbers[i] < 0) continue; 
792       plugin->AddRunNumber(fRunNumbers[i]);
793     }
794     
795     // Set the working directory to be the trains name (with special
796     // characters replaced by '_' and the date appended), and also set
797     // the output directory (relative to working directory)
798     plugin->SetGridWorkingDir(name.Data());
799     plugin->SetGridOutputDir("output");
800
801     // Enable configured PARs 
802     TIter nextPar(&fListOfPARs);
803     TObject* parName;
804     while ((parName = nextPar()))
805       plugin->EnablePackage(parName->GetName());
806     
807     // Add sources that need to be compiled on the workers using
808     // AcLIC. 
809     TString addSources = SetupSources();
810     if (!addSources.IsNull()) plugin->SetAnalysisSource(addSources.Data());
811
812     // Add binary libraries that should be uploaded to the workers 
813     TString addLibs = SetupLibraries();
814     if (!addLibs.IsNull()) plugin->SetAdditionalLibs(addLibs.Data());
815     
816     // Disable default outputs 
817     plugin->SetDefaultOutputs(true);
818
819     // Merge parameters 
820     plugin->SetMaxMergeFiles(20);
821     plugin->SetMergeExcludes("AliAOD.root "
822                             "EventStat_temp.root "
823                             "*event_stat*.root");
824
825     // Set number of runs per master - set to one to per run
826     plugin->SetNrunsPerMaster(1);
827
828     // Loop over defined containers in the analysis manager, 
829     // and declare these as outputs 
830     TString listOfAODs  = "";
831     TString listOfHists = "";
832     AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager();
833     AliAnalysisDataContainer* cont = 0;
834     TIter nextCont(mgr->GetOutputs());
835     while ((cont = static_cast<AliAnalysisDataContainer*>(nextCont()))) {
836       TString outName(cont->GetFileName());
837       TString& list = (outName == "default" ? listOfAODs : listOfHists);
838       if (outName == "default") { 
839         if (!mgr->GetOutputEventHandler()) continue; 
840
841         outName = mgr->GetOutputEventHandler()->GetOutputFileName();
842       }
843       if (list.Contains(outName)) continue;
844       if (!list.IsNull()) list.Append(",");
845       list.Append(outName);
846     }
847     if (!mgr->GetExtraFiles().IsNull()) { 
848       if (!listOfAODs.IsNull()) listOfAODs.Append("+");
849       TString extra = mgr->GetExtraFiles();
850       extra.ReplaceAll(" ", ",");
851       listOfAODs.Append(extra);
852     }
853     TString outArchive = Form("stderr, stdout@disk=%d", fNReplica);
854     if (!listOfHists.IsNull()) 
855       outArchive.Append(Form(" hist_archive.zip:%s@disk=%d", 
856                              listOfHists.Data(), fNReplica));
857     if (!listOfAODs.IsNull()) 
858       outArchive.Append(Form(" aod_archive.zip:%s@disk=%d", 
859                              listOfAODs.Data(), fNReplica));
860     if (listOfAODs.IsNull() && listOfHists.IsNull()) 
861       Fatal("CreateGridHandler", "No outputs defined");
862     // Disabled for now 
863     // plugin->SetOutputArchive(outArchive);
864     
865     // Set name of generated analysis macro 
866     plugin->SetAnalysisMacro(Form("%s.C", name.Data()));
867     
868     // Maximum number of sub-jobs 
869     // plugin->SetSplitMaxInputFileNumber(25);
870     
871     // Set the Time-To-Live 
872     plugin->SetTTL(70000);
873     
874     // Re-submit failed jobs as long as the ratio of failed jobs is
875     // below this percentage. 
876     plugin->SetMasterResubmitThreshold(95);
877
878     // Set the input format
879     plugin->SetInputFormat("xml-single");
880
881     // Set the name of the generated jdl 
882     plugin->SetJDLName(Form("%s.jdl", name.Data()));
883
884     // Set the name of the generated executable 
885     plugin->SetExecutable(Form("%s.sh", name.Data()));
886     
887     // Set the job price !?
888     plugin->SetPrice(1);
889
890     // Set whether to merge via JDL 
891     plugin->SetMergeViaJDL(true);
892     
893     // Fast read otion 
894     plugin->SetFastReadOption(false);
895
896     // Whether to overwrite existing output 
897     plugin->SetOverwriteMode(true);
898
899     // Set the executable binary name and options 
900     plugin->SetExecutableCommand("aliroot -b -q -x");
901     
902     // Split by storage element - must be lower case!
903     plugin->SetSplitMode("se");
904
905     return plugin;
906   }
907   //__________________________________________________________________
908   /** 
909    * Create input handler 
910    * 
911    * @param type 
912    * 
913    * @return 
914    */
915   virtual AliVEventHandler* CreateInputHandler(EType type)
916   {
917     switch (type) {
918     case kESD: return new AliESDInputHandler(); 
919     case kAOD: return new AliAODInputHandler(); 
920     }
921     return 0;
922   }
923   //__________________________________________________________________
924   /** 
925    * Create input handler 
926    * 
927    * @param type  Run type (ESD or AOD)
928    * @param mc    Assume monte-carlo input 
929    * 
930    * @return 
931    */
932   virtual AliVEventHandler* CreateMCHandler(EType type, bool mc)
933   {
934     if (!mc || type != kESD) return 0;
935     AliMCEventHandler* mcHandler = new AliMCEventHandler();
936     mcHandler->SetReadTR(true); 
937     return mcHandler;
938   }
939   //__________________________________________________________________
940   /** 
941    * Create output event handler 
942    * 
943    * @param type 
944    * 
945    * @return 
946    */
947   virtual AliVEventHandler* CreateOutputHandler(EType type)
948   {
949     switch (type) { 
950     case kESD: // Fall through 
951     case kAOD: { 
952       AliAODHandler* ret = new AliAODHandler();
953       ret->SetOutputFileName("AliAOD.root");
954       return ret;
955     }
956     }
957     return 0;
958   }
959   //__________________________________________________________________
960   /** 
961    * Create physics selection , and add to manager
962    * 
963    * @param mc Whether this is for MC 
964    */
965   virtual void CreatePhysicsSelection(Bool_t mc,
966                                       AliAnalysisManager* mgr)
967   {
968     gROOT->Macro(Form("AddTaskPhysicsSelection.C(%d)", mc));
969     mgr->RegisterExtraFile("event_stat.root");
970   }
971   //__________________________________________________________________
972   /** 
973    * Create analysis tasks 
974    * 
975    * @param mode Run mode
976    * @param mgr  Manager
977    * @param par  Whether to use pars 
978    */
979   virtual void CreateTasks(EMode mode, Bool_t par, AliAnalysisManager* mgr)=0;
980   //__________________________________________________________________
981   /** 
982    * Connect to external services (Proof and/or grid)
983    * 
984    * @param mode Running mode 
985    * 
986    * @return true on success 
987    */
988   virtual Bool_t Connect(EMode mode)
989   {
990     if (mode == kLocal) return true;
991                           
992     // --- Set-up connections to Proof cluster and alien -------------
993     if (mode == kProof) { 
994       // --- Find user name ------------------------------------------
995       TString userName(gSystem->Getenv("alien_API_USER"));
996       if (userName.IsNull()) {
997         userName = gSystem->GetUserInfo()->fUser;
998         Warning("Connect", 
999                 "environment variable 'alien_API_USER' not set, using %s", 
1000                 userName.Data());
1001       }
1002
1003       // --- Set prefered GSI method ---------------------------------
1004       gEnv->SetValue("XSec.GSI.DelegProxy", "2");
1005       
1006       // --- Now open connection to PROOF cluster --------------------
1007       TString serv = "";
1008       Bool_t  lite = false;
1009       if (fProofServer.BeginsWith("workers=") || fProofServer.IsNull()) {
1010         lite = true;
1011         serv = fProofServer;
1012       }
1013       else 
1014         serv = Form("%s@%s", userName.Data(), fProofServer.Data());
1015       TProof::Open(serv);
1016       if (!gProof) { 
1017         Error("Connect", "Failed to connect to Proof cluster %s as %s",
1018               fProofServer.Data(), userName.Data());
1019         return false;
1020       }
1021       if (lite) return true;
1022     }
1023
1024     // --- Open a connection to the grid -----------------------------
1025     TGrid::Connect("alien://");
1026     if (!gGrid || !gGrid->IsConnected()) { 
1027       // This is only fatal in grid mode 
1028       Error("Connect", "Failed to connect to AliEN");
1029       if (mode == kGrid) return false; 
1030       return true;
1031     }
1032     if (mode == kGrid) return true;
1033
1034     
1035     // --- Set and make output directory -----------------------------
1036     TString name = EscapedName();
1037     TString homeDir(gGrid->GetHomeDirectory());
1038     TString workDir(homeDir);
1039     workDir.Append("/");
1040     workDir.Append(name);
1041     
1042     // Make working directory 
1043     if (!gGrid->Cd(workDir)) { 
1044       gGrid->Cd(homeDir);
1045       if (gGrid->Mkdir(workDir)) {
1046         gGrid->Cd(name);
1047         Info("Connect", "Directory %s created", workDir.Data());
1048       }
1049     }
1050     // Make output directory 
1051     gGrid->Mkdir("proof_output");
1052     gGrid->Cd("proof_output");
1053
1054     return true;
1055   }       
1056   //__________________________________________________________________
1057   /** 
1058    * Load common libraries 
1059    * 
1060    * @param mode Running mode                   
1061    * @param par  If true, load as PARs 
1062    * 
1063    * @return true on success 
1064    */
1065   Bool_t LoadCommonLibraries(EMode mode, Bool_t par) 
1066   {
1067     if (!gSystem->Getenv("ALICE_ROOT")) { 
1068       Error("LoadCommonLibraries", "Local AliROOT not available");
1069       return false;
1070     }
1071     gSystem->Load("libTree.so");
1072     gSystem->Load("libGeom.so");
1073     gSystem->Load("libVMC.so");
1074     gSystem->Load("libPhysics.so");
1075     gSystem->Load("libMinuit.so");
1076
1077     Bool_t ret   = true;
1078     Bool_t basic = mode == kGrid ? false : par;
1079     
1080     ret &= LoadLibrary("STEERBase",     mode, basic, false);
1081     ret &= LoadLibrary("ESD",           mode, basic, false);
1082     ret &= LoadLibrary("AOD",           mode, basic, false);
1083     ret &= LoadLibrary("ANALYSIS",      mode, basic, true);
1084     ret &= LoadLibrary("ANALYSISalice", mode, basic, true);
1085
1086     return ret;
1087   }
1088   //__________________________________________________________________
1089   /** 
1090    * Load a library 
1091    * 
1092    * @param what What library to load
1093    * @param mode Mode (local, proof, grid)
1094    * @param par  If true, load as PAR
1095    * @param rec  If true, also load on slaves
1096    * 
1097    * @return true on success 
1098    */
1099   Bool_t LoadLibrary(const char* what, EMode mode, Bool_t par, Bool_t rec=false)
1100   {
1101     if (!what || what[0] == '\0') return true;
1102     
1103     TString module(what);
1104     TString libName(what);
1105     if (!libName.BeginsWith("lib")) libName = Form("lib%s", libName.Data());
1106     if (!libName.EndsWith(".so"))   libName.Append(".so");
1107
1108     Int_t ret = 0;
1109
1110     switch (mode) { 
1111     case kLocal: // Just load and exit 
1112       gSystem->Load(libName.Data());
1113       break;
1114     case kGrid: 
1115       if (par) { 
1116         ret = SetupPAR(what) ? 0 : -1;
1117         if (rec) fListOfPARs.Add(new TObjString(what));
1118       } else  {
1119         ret = gSystem->Load(libName.Data());
1120         if (rec) fListOfLibraries.Add(new TObjString(libName));
1121       }
1122       break;
1123     case kProof: 
1124       ret = gProof->UploadPackage(what);
1125       if (ret < 0)  {   
1126           ret = gProof->UploadPackage(gSystem->ExpandPathName(Form("../%s.par",
1127                                                                    what)));
1128         if (ret < 0) {  
1129           ret = 
1130             gProof->UploadPackage(gSystem
1131                                   ->ExpandPathName(Form("$ALICE_ROOT/%s.par", 
1132                                                         what)));
1133           if (ret < 0) {
1134             Error("LoadLibrary", 
1135                   "Could not find module %s.par in current directory nor "
1136                   "in $ALICE_ROOT", module.Data());
1137             return false;
1138           }
1139         }
1140       }
1141       ret = gProof->EnablePackage(what);
1142       break;
1143     }
1144     if (ret < 0) { 
1145       Error("LoadLibrary", "Couldn't load %s", what);
1146       return false;
1147     }
1148     return true;
1149   }
1150           
1151   //__________________________________________________________________
1152   Bool_t SetupPAR(const char* what)
1153   {
1154     if (!what || what[0] == '\0') return -1;
1155     
1156     TString parFile(Form("%s.par", what));
1157     if (gSystem->AccessPathName(parFile.Data())) { 
1158       if (gSystem->AccessPathName(Form("../%s.par", what))) { 
1159         // If not found 
1160         TString aliParFile = 
1161           gSystem->ExpandPathName(Form("$(ALICE_ROOT)/%s.par", what));
1162         if (gSystem->AccessPathName(aliParFile.Data())) { 
1163           Error("SetupPAR", "PAR file %s not found in current directory or "
1164                 "$(ALICE_ROOT)", what);
1165           return false;
1166         }
1167         // Copy to current directory 
1168         TFile::Cp(aliParFile, parFile);
1169       }
1170       else 
1171         gSystem->Exec(Form("ln -s ../%s.par .", what));
1172     }
1173     
1174     // Extract archive 
1175     gSystem->Exec(Form("tar xvzf %s", parFile.Data()));
1176     
1177     // Change directory into par archive
1178     TString cwd = gSystem->WorkingDirectory();
1179     
1180     if (!gSystem->ChangeDirectory(what)) { 
1181       Error("SetupPAR", "Failed to change directory to %s", what);
1182       return false;
1183     }
1184     
1185     // Test the build 
1186     if (!gSystem->AccessPathName("PROOF-INF/BUILD.sh")) {
1187       Info("SetupPar", "Building in PAR archive %s", what);
1188       if (gSystem->Exec("PROOF-INF/BUILD.sh")) { 
1189         Error("SetupPar", "Failed to build in PAR directory %s", what);
1190         gSystem->ChangeDirectory(cwd.Data());
1191         return false;
1192       }
1193     }
1194     
1195     // Check for setup script
1196     if (!gSystem->AccessPathName("PROOF-INF/SETUP.C")) {
1197       Info("SetupPAR", "Setting up for PAR %s", what);
1198       gROOT->Macro("PROOF-INF/SETUP.C");
1199     }
1200     if (!gSystem->ChangeDirectory(cwd.Data())) return false;
1201
1202     return true;
1203   }
1204   //__________________________________________________________________
1205   TString SetupExtras()
1206   {
1207     TString ret;
1208     TIter next(&fListOfExtras);
1209     TObjString* obj = 0;
1210     while ((obj = static_cast<TObjString*>(next()))) {
1211       TString path = gSystem->ExpandPathName(obj->GetName());
1212       if (!path.BeginsWith("/")) 
1213         // If not an absolute path, prepend to up-one
1214         path = Form("../%s", path.Data());
1215       if (gSystem->AccessPathName(path.Data())) { 
1216         // File not accessible 
1217         Warning("SetupExtras", "File %s not accessible", path.Data());
1218         continue;
1219       }
1220       ret.Append(Form("%s ", gSystem->BaseName(obj->GetName())));
1221       gSystem->Exec(Form("ln -s %s .", path.Data()));
1222     }
1223     ret = ret.Strip();
1224     return ret;
1225   }
1226   //__________________________________________________________________
1227   TString SetupSources()
1228   {
1229     TString nam = EscapedName();
1230     TString ret;
1231     TIter next(&fListOfSources); 
1232     TObject* src;
1233     while ((src = next())) {
1234       TString path = gSystem->ExpandPathName(src->GetName());
1235       if (!path.BeginsWith("/")) 
1236         // If not an absolute path, prepend to up-one
1237         path = Form("../%s", path.Data());
1238       if (gSystem->AccessPathName(path.Data())) { 
1239         // File not accessible 
1240         Warning("SetupSources", "File %s not accessible", path.Data());
1241         continue;
1242       }
1243       ret.Append(Form("%s ", gSystem->BaseName(src->GetName())));
1244       gSystem->Exec(Form("ln -s %s .", path.Data()));
1245     }
1246     ret = ret.Strip();
1247     return ret;
1248   }
1249   //__________________________________________________________________
1250   TString SetupLibraries()
1251   {
1252     TString ret;
1253     TIter next(&fListOfLibraries); 
1254     TObject* lib;
1255     while ((lib = next())) {
1256       ret.Append(lib->GetName());
1257       ret.Append(" ");
1258     }
1259     // Also add extra files to this variable 
1260     ret.Append(SetupExtras());
1261     ret = ret.Strip();
1262     return ret;
1263   }
1264   //__________________________________________________________________
1265   /** 
1266    * Scan directory @a dir (possibly recursive) for tree files to add
1267    * to the chain.  
1268    * 
1269    * @param dir        Directory to scan
1270    * @param chain      Chain to add to
1271    * @param type       Type of tree (ESD or AOD)
1272    * @param recursive  Whether to scan recursively 
1273    *
1274    * @return true if any files where added 
1275    */
1276   Bool_t ScanDirectory(TSystemDirectory* dir, TChain* chain, 
1277                        EType type, bool recursive)
1278   {
1279     TString fnPattern;
1280     switch (type) { 
1281     case kESD:  fnPattern = "AliESD"; break;
1282     case kAOD:  fnPattern = "AliAOD"; break;
1283     }
1284     Info("ScanDirectory", "Now investigating %s for %s", 
1285          dir->GetName(), fnPattern.Data());
1286
1287     // Assume failure 
1288     Bool_t ret = false;
1289
1290     // Get list of files, and go back to old working directory
1291     TString oldDir(gSystem->WorkingDirectory());
1292     TList* files = dir->GetListOfFiles();
1293     gSystem->ChangeDirectory(oldDir);
1294     if (!files) return false;
1295
1296     // Sort list of files and check if we should add it 
1297     files->Sort();
1298     TIter next(files);
1299     TSystemFile* file = 0;
1300     while ((file = static_cast<TSystemFile*>(next()))) {
1301       TString name(file->GetName());
1302     
1303       // Ignore special links 
1304       if (name == "." || name == "..") continue;
1305
1306       // Check if this is a directory 
1307       if (file->IsDirectory()) { 
1308         if (recursive) 
1309           if (ScanDirectory(static_cast<TSystemDirectory*>(file),
1310                             chain,type,recursive))
1311             ret = true;;
1312         continue;
1313       }
1314     
1315       // If this is not a root file, ignore 
1316       if (!name.EndsWith(".root")) continue;
1317
1318       // If this file does not contain AliESDs, ignore 
1319       if (!name.Contains(fnPattern)) continue;
1320     
1321       // Get the path 
1322       TString fn(Form("%s/%s", file->GetTitle(), name.Data()));
1323
1324       // Add 
1325       Info("ScanDirectory", "Adding %s", fn.Data());
1326       chain->Add(fn);
1327       ret = true;
1328     }
1329     return ret;
1330   }
1331   //__________________________________________________________________
1332   /** 
1333    * Create a chain from an XML containing an collection
1334    * 
1335    * @param treeName Name of tree's 
1336    * @param xmlFile  XML collection
1337    * 
1338    * @return Newly allocated chain or null
1339    */
1340   TChain* CreateChainFromXML(const char* treeName, 
1341                              const char* xmlFile) 
1342   {
1343     TGridCollection* collection = TAlienCollection::Open(xmlFile);
1344     if (!collection) { 
1345       Error("CreateChainFromXML", "Cannot create AliEn collection from "
1346             "XML file %s", xmlFile);
1347       return 0;
1348     }
1349
1350     TChain* chain = new TChain(treeName);
1351     collection->Reset();
1352     while (collection->Next()) chain->Add(collection->GetTURL(""));
1353     
1354     return chain;
1355   }
1356   //__________________________________________________________________
1357   /** 
1358    * Create a chain of data 
1359    * 
1360    * @param type Type of data
1361    * @param mode Operation mode 
1362    * 
1363    * @return TChain of data 
1364    */    
1365   TChain* CreateChain(EType type, EMode mode, EOper /* oper */)
1366   {
1367     TString treeName;
1368     switch (type) { 
1369     case kESD:  treeName = "esdTree"; break;
1370     case kAOD:  treeName = "aodTree"; break;
1371     }
1372
1373     TChain* chain = 0;
1374     switch (mode) { 
1375     case kProof: 
1376       if (!fDataSet.IsNull()) break; 
1377       // Otherwise fall through
1378     case kLocal:
1379       if (fXML.IsNull()) {
1380         chain = new TChain(treeName.Data());
1381         TString dir(fDataDir);
1382         if (!dir.BeginsWith("/")) dir = Form("../%s", dir.Data());
1383         TSystemDirectory d(dir.Data(), dir.Data());
1384         if (!ScanDirectory(&d, chain, type, true)) { 
1385           delete chain;
1386           chain = 0;
1387         }
1388       }
1389       else 
1390         chain = CreateChainFromXML(treeName.Data(), fXML.Data());
1391       break;
1392     case kGrid:  break; // Do nothing - we use plugin
1393     }
1394     
1395     if (chain && chain->GetNtrees() <= 0) { 
1396       delete chain;
1397       return 0;
1398     }
1399     return chain;
1400   }
1401   //__________________________________________________________________
1402   TString fName;             // Name of analysis
1403   TString fRootVersion;      // ROOT version to use 
1404   TString fAliRootVersion;   // AliROOT version to use 
1405   TString fProofServer;      // Name of proof server
1406   TString fDataDir;          // Grid Input directory 
1407   TString fDataSet;          // Proof data set name 
1408   TString fXML;              // XML collection for local/proof mode
1409   TArrayI fRunNumbers;       // List of run number 
1410   TList   fListOfPARs;       // List of PAR files to use 
1411   TList   fListOfSources;    // List of sources to upload and AcLIC
1412   TList   fListOfLibraries;  // List of libraries to load
1413   TList   fListOfExtras;     // List of extra files to upload
1414   Int_t   fNReplica;         // Storage replication
1415   Int_t   fESDPass;
1416   TString fEscapedName;
1417   Bool_t  fAllowOverwrite;
1418 };
1419
1420 //====================================================================
1421 /**
1422  * Analysis train to do energy loss fits
1423  * 
1424  * @ingroup pwg2_forward_scripts_makers
1425  */
1426 class ForwardELoss : public TrainSetup
1427 {
1428 public:
1429   /** 
1430    * Constructor.  Date and time must be specified when running this
1431    * in Termiante mode on Grid
1432    * 
1433    * @param dateTime Append date and time to name 
1434    * @param year     Year
1435    * @param month    Month 
1436    * @param day      Day
1437    * @param hour     Hour 
1438    * @param min      Minutes
1439    */
1440   ForwardELoss(Bool_t   dateTime, 
1441                UShort_t year  = 0, 
1442                UShort_t month = 0, 
1443                UShort_t day   = 0, 
1444                UShort_t hour  = 0, 
1445                UShort_t min   = 0) 
1446     : TrainSetup("Forward energy loss", dateTime, 
1447                  year, month, day, hour, min) 
1448   {}
1449   /** 
1450    * Run this analysis 
1451    * 
1452    * @param mode     Mode
1453    * @param oper     Operation
1454    * @param nEvents  Number of events (negative means all)
1455    * @param mc       If true, assume simulated events 
1456    */
1457   void Run(const char* mode, const char* oper, 
1458            Int_t nEvents=-1, Bool_t mc=false)
1459   {
1460     EMode eMode = ParseMode(mode);
1461     EOper eOper = ParseOperation(oper);
1462     
1463     Run(eMode, eOper, nEvents, mc);
1464   }
1465   /** 
1466    * Run this analysis 
1467    * 
1468    * @param mode     Mode
1469    * @param oper     Operation
1470    * @param nEvents  Number of events (negative means all)
1471    * @param mc       If true, assume simulated events 
1472    */
1473   void Run(EMode mode, EOper oper, Int_t nEvents=-1, Bool_t mc=false)
1474   {
1475     Exec(kESD, mode, oper, nEvents, mc, true);
1476   }
1477   /** 
1478    * Create the tasks 
1479    * 
1480    * @param mode Processing mode
1481    * @param par  Whether to use par files 
1482    * @param mgr  Analysis manager 
1483    */
1484   void CreateTasks(EMode mode, Bool_t par, AliAnalysisManager* mgr)
1485   {
1486     // --- Output file name ------------------------------------------
1487     AliAnalysisManager::SetCommonFileName("forward_eloss.root");
1488
1489     // --- Load libraries/pars ---------------------------------------
1490     LoadLibrary("PWG2forward2", mode, par, true);
1491     
1492     // --- Set load path ---------------------------------------------
1493     gROOT->SetMacroPath(Form("%s:$(ALICE_ROOT)/PWG2/FORWARD/analysis2",
1494                              gROOT->GetMacroPath()));
1495
1496     // --- Check if this is MC ---------------------------------------
1497     Bool_t mc = mgr->GetMCtruthEventHandler() != 0;
1498
1499     // --- Add the task ----------------------------------------------
1500     gROOT->Macro(Form("AddTaskForwardMultEloss.C(%d)", mc));
1501   }
1502 };
1503
1504 //====================================================================
1505 /**
1506  * Analysis train to make Forward and Central multiplicity
1507  * 
1508  * @ingroup pwg2_forward_scripts_makers
1509  * @ingroup pwg2_forward_aod
1510  */
1511 class MakeAODTrain : public TrainSetup
1512 {
1513 public:
1514   /** 
1515    * Constructor.  Date and time must be specified when running this
1516    * in Termiante mode on Grid
1517    * 
1518    * @param dateTime Append date and time to name 
1519    * @param sys      Collision system (1: pp, 2: PbPb)
1520    * @param sNN      Center of mass energy [GeV]
1521    * @param field    L3 magnetic field - one of {-5,0,+5} kG
1522    * @param year     Year     - if not specified, current year
1523    * @param month    Month    - if not specified, current month
1524    * @param day      Day      - if not specified, current day
1525    * @param hour     Hour     - if not specified, current hour
1526    * @param min      Minutes  - if not specified, current minutes
1527    */
1528   MakeAODTrain(const  char* name, 
1529                UShort_t     sys      = 0, 
1530                UShort_t     sNN      = 0, 
1531                Short_t      field    = 0, 
1532                Bool_t       useCent  = false, 
1533                Bool_t       dateTime = false, 
1534                UShort_t     year     = 0, 
1535                UShort_t     month    = 0, 
1536                UShort_t     day      = 0, 
1537                UShort_t     hour     = 0, 
1538                UShort_t     min      = 0) 
1539     : TrainSetup(name, dateTime, 
1540                  year, month, day, hour, min),
1541       fSys(sys), 
1542       fSNN(sNN), 
1543       fField(field),
1544       fUseCent(useCent)
1545   {}
1546   /** 
1547    * Run this analysis 
1548    * 
1549    * @param mode     Mode
1550    * @param oper     Operation
1551    * @param nEvents  Number of events (negative means all)
1552    * @param mc       If true, assume simulated events 
1553    * @param usePar   If true, use PARs 
1554    */
1555   void Run(const char* mode, const char* oper, 
1556            Int_t nEvents=-1, Bool_t mc=false,
1557            Bool_t usePar=false)
1558   {
1559     Exec("ESD", mode, oper, nEvents, mc, usePar);
1560   }
1561   /** 
1562    * Run this analysis 
1563    * 
1564    * @param mode     Mode
1565    * @param oper     Operation
1566    * @param nEvents  Number of events (negative means all)
1567    * @param mc       If true, assume simulated events 
1568    * @param usePar   If true, use PARs 
1569    */
1570   void Run(EMode mode, EOper oper, Int_t nEvents=-1, Bool_t mc=false, 
1571            Bool_t usePar = false)
1572   {
1573     Exec(kESD, mode, oper, nEvents, mc, usePar);
1574   }
1575 protected:
1576   /** 
1577    * Create the tasks 
1578    * 
1579    * @param mode Processing mode
1580    * @param par  Whether to use par files 
1581    * @param mgr  Analysis manager 
1582    */
1583   void CreateTasks(EMode mode, Bool_t par, AliAnalysisManager* mgr)
1584   {
1585     // --- Output file name ------------------------------------------
1586     AliAnalysisManager::SetCommonFileName("forward.root");
1587
1588     // --- Load libraries/pars ---------------------------------------
1589     LoadLibrary("PWG2forward2", mode, par, true);
1590     
1591     // --- Set load path ---------------------------------------------
1592     gROOT->SetMacroPath(Form("%s:$(ALICE_ROOT)/PWG2/FORWARD/analysis2",
1593                              gROOT->GetMacroPath()));
1594
1595     // --- Check if this is MC ---------------------------------------
1596     Bool_t mc = mgr->GetMCtruthEventHandler() != 0;
1597     
1598     // --- Centrality ------------------------------------------------
1599     if (fUseCent) gROOT->Macro("AddTaskCentrality.C");
1600     
1601     // --- Add the task ----------------------------------------------
1602     gROOT->Macro(Form("AddTaskForwardMult.C(%d,%d,%d,%d)", 
1603                       mc, fSys, fSNN, fField));
1604     AddExtraFile(gSystem->Which(gROOT->GetMacroPath(), "ForwardAODConfig.C"));
1605
1606     // --- Add the task ----------------------------------------------
1607     gROOT->Macro(Form("AddTaskCentralMult.C(%d,%d,%d)", 
1608                       fSys, fSNN, fField));
1609   }
1610   //__________________________________________________________________
1611   /** 
1612    * Create physics selection , and add to manager
1613    * 
1614    * @param mc Whether this is for MC 
1615    */
1616   void CreatePhysicsSelection(Bool_t mc,
1617                               AliAnalysisManager* mgr)
1618   {
1619     gROOT->Macro(Form("AddTaskPhysicsSelection.C(%d)", mc));
1620     mgr->RegisterExtraFile("event_stat.root");
1621
1622     // --- Get input event handler -----------------------------------
1623     AliInputEventHandler* ih =
1624       static_cast<AliInputEventHandler*>(mgr->GetInputEventHandler());
1625     
1626     // --- Get Physics selection -------------------------------------
1627     AliPhysicsSelection* ps = 
1628       static_cast<AliPhysicsSelection*>(ih->GetEventSelection());
1629
1630     // --- Ignore trigger class when selecting events.  This means ---
1631     // --- that we get offline+(A,C,E) events too --------------------
1632     ps->SetSkipTriggerClassSelection(true);
1633   }
1634   UShort_t fSys;
1635   UShort_t fSNN;
1636   Short_t  fField;
1637   Bool_t   fUseCent;
1638 };
1639 //====================================================================
1640 /**
1641  * Analysis train to make @f$ dN/d\eta@f$
1642  * 
1643  * @ingroup pwg2_forward_scripts_makers
1644  * @ingroup pwg2_forward_dndeta
1645  */
1646 class MakedNdetaTrain : public TrainSetup
1647 {
1648 public:
1649   /** 
1650    * Constructor.  Date and time must be specified when running this
1651    * in Termiante mode on Grid
1652    * 
1653    * @param trig     Trigger to use 
1654    * @param vzMin    Least @f$ v_z@f$
1655    * @param vzMax    Largest @f$ v_z@f$
1656    * @param scheme   Normalisation scheme 
1657    * @param useCent  Whether to use centrality 
1658    * @param dateTime Append date and time to name 
1659    * @param year     Year     - if not specified, current year
1660    * @param month    Month    - if not specified, current month
1661    * @param day      Day      - if not specified, current day
1662    * @param hour     Hour     - if not specified, current hour
1663    * @param min      Minutes  - if not specified, current minutes
1664    */
1665   MakedNdetaTrain(const char* name, 
1666                   const char* trig="INEL", 
1667                   Double_t    vzMin=-10, 
1668                   Double_t    vzMax=10, 
1669                   const char* scheme="FULL", 
1670                   Bool_t      useCent=false,
1671                   Bool_t      dateTime=false,
1672                   UShort_t    year  = 0, 
1673                   UShort_t    month = 0, 
1674                   UShort_t    day   = 0, 
1675                   UShort_t    hour  = 0, 
1676                   UShort_t    min   = 0) 
1677     : TrainSetup(name, dateTime, year, month, day, hour, min),
1678       fTrig(trig), 
1679       fVzMin(vzMin), 
1680       fVzMax(vzMax),
1681       fScheme(scheme),
1682       fUseCent(useCent)
1683   {}
1684   /** 
1685    * Run this analysis 
1686    * 
1687    * @param mode     Mode
1688    * @param oper     Operation
1689    * @param nEvents  Number of events (negative means all)
1690    * @param mc       If true, assume simulated events 
1691    * @param usePar   If true, use PARs 
1692    */
1693   void Run(const char* mode, const char* oper, 
1694            Int_t nEvents=-1, Bool_t usePar=false)
1695   {
1696     Exec("AOD", mode, oper, nEvents, false, usePar);
1697   }
1698   /** 
1699    * Run this analysis 
1700    * 
1701    * @param mode     Mode
1702    * @param oper     Operation
1703    * @param nEvents  Number of events (negative means all)
1704    * @param mc       If true, assume simulated events 
1705    * @param usePar   If true, use PARs 
1706    */
1707   void Run(EMode mode, EOper oper, Int_t nEvents=-1, 
1708            Bool_t usePar=false)
1709   {
1710     Exec(kAOD, mode, oper, nEvents, false, usePar);
1711   }
1712   /** 
1713    * Set the trigger to use (INEL, INEL>0, NSD)
1714    * 
1715    * @param trig Trigger to use 
1716    */
1717   void SetTrigger(const char* trig) { fTrig = trig; }
1718   /** 
1719    * Set the vertex range to accept 
1720    * 
1721    * @param min Minimum 
1722    * @param max Maximum 
1723    */
1724   void SetVertexRange(Double_t min, Double_t max) { fVzMin=min; fVzMax=max; }
1725   /** 
1726    * Set the normalisation scheme 
1727    * 
1728    * @param scheme Normalisation scheme options 
1729    */
1730   void SetScheme(const char* scheme) { fScheme = scheme; }
1731   /** 
1732    * Whether to use centrality or not 
1733    * 
1734    * @param use To use the centrality 
1735    */
1736   void SetUseCentrality(Bool_t use) { fUseCent = use; }
1737 protected:
1738   /** 
1739    * Create the tasks 
1740    * 
1741    * @param mode Processing mode
1742    * @param par  Whether to use par files 
1743    * @param mgr  Analysis manager 
1744    */
1745   void CreateTasks(EMode mode, Bool_t par, AliAnalysisManager*)
1746   {
1747     // --- Output file name ------------------------------------------
1748     AliAnalysisManager::SetCommonFileName("forward_dndeta.root");
1749
1750     // --- Load libraries/pars ---------------------------------------
1751     LoadLibrary("PWG2forward2", mode, par, true);
1752     
1753     // --- Set load path ---------------------------------------------
1754     gROOT->SetMacroPath(Form("%s:$(ALICE_ROOT)/PWG2/FORWARD/analysis2",
1755                              gROOT->GetMacroPath()));
1756
1757     // --- Add the task ----------------------------------------------
1758     gROOT->Macro(Form("AddTaskForwarddNdeta.C(\"%s\",%f,%f,%d,\"%s\")",
1759                       fTrig.Data(), fVzMin, fVzMax, fUseCent, fScheme.Data()));
1760
1761     gROOT->Macro(Form("AddTaskCentraldNdeta.C(\"%s\",%f,%f,%d,\"%s\")",
1762                       fTrig.Data(), fVzMin, fVzMax, fUseCent, fScheme.Data()));
1763   }
1764   //__________________________________________________________________
1765   /** 
1766    * Do nothing 
1767    * 
1768    */
1769   void CreatePhysicsSelection(Bool_t,AliAnalysisManager*) {}
1770   /** 
1771    * Crete output handler - we don't want one here. 
1772    * 
1773    * @return 0
1774    */
1775   AliVEventHandler* CreateOutputHandler(EType) { return 0; }
1776   TString  fTrig;      // Trigger to use 
1777   Double_t fVzMin;     // Least v_z
1778   Double_t fVzMax;     // Largest v_z
1779   TString  fScheme;    // Normalisation scheme 
1780   Bool_t   fUseCent;   // Use centrality 
1781 };
1782   
1783 //____________________________________________________________________
1784 //
1785 // EOF
1786 //