Fixes to track selection for embedding in cluster task (Bastian), Do no select events...
[u/mrichter/AliRoot.git] / PWG4 / macros / AnalysisTrainPWG4Jets.C
1 //===================== ANALYSIS TRAIN =========================================
2 // To use: copy this macro to your work directory, modify the global part to match
3 // your needs, then run root.
4 //    root[0] .L AnalysisTrain.C
5 // Grid full mode as below (other modes: test, offline, submit, terminate)
6 //    root[1] AnalysisTrainPWG-244Jets("grid", "full")
7 // CAF mode (requires root v5-23-02 + aliroot v4-16-Rev08)
8 //    root[2] AnalysisTrainPWG4Jets("proof")
9 // Local mode requires AliESds.root or AliAOD.root in ./data directory
10 //    root[3] AnalysisTrainPWG4Jets("local")
11 // In proof and grid modes, a token is needed and sourcing the produced environment file.
12 //
13 // If 'saveTrain' flag is set, the train will generate a directory name and run
14 // in this directory. A configuration file 'ConfigTrain.C' will be generated. 
15 // One can replay at any time the train via:
16 //    root[1] AnalysisTrainPWG4Jets(ana_mode, plugin_mode, "train_default_<date>/ConfigTrain.C")
17
18 // For Usage with fastjet run in "offline" first and then "submit"
19 // jdl and analysismacro are automatically patched after "offline" mode
20
21 // =============================================================================
22 // ### General Steering variables
23 // =============================================================================
24 //== general setup variables
25 TString     kTrainName         = "testAnalysis"; // *CHANGE ME* (no blancs or special characters)
26 TString     kJobTag            = "PWG4 Jet Tasks analysis train configured"; // *CHANGE ME*
27
28 // Usage of par files ONLY in grid mode and ONLY if the code is not available
29 // in the deployed AliRoot versions. Par file search path: local dir, if not there $ALICE_ROOT.
30 // To refresh par files, remove the ones in the workdir, then do "make <target.par>" in 
31 // AliRoot.
32 Bool_t      kUsePAR             = kFALSE;  // use par files for extra libs
33 Bool_t      kUseCPAR            = kFALSE;  // use par files for common libs
34 Bool_t      kFillAOD = kTRUE;  // switch of AOD filling for on the fly analysis
35 Bool_t      kFilterAOD = kTRUE;
36 Int_t       kSaveAOD = 8;        // Bit switch 1 = Full AOD 2 = Jet AOD , 4 = PartCorr, 8 = JCORRAN 
37 //== general input and output variables
38
39 Int_t       iAODanalysis       = 1;      // Analysis on input AOD's
40 Int_t       iAODhandler        = 1;      // Analysis produces an AOD or dAOD's
41 Int_t       iCentralitySelection  = 0;      // Use the centrality
42 Int_t       iESDfilter         = 0;      // ESD to AOD filter (barrel + muon tracks)
43 Int_t       iPhysicsSelection  = 1;      // ESD to AOD filter (barrel + muon tracks)
44 UInt_t      iPhysicsSelectionFlag = 1; // set by pyshics selection and passed to the task, kMB, kUserDefined etc
45 Bool_t      useTender           = kFALSE; // use tender wagon 
46 Bool_t      kUseKinefilter     = kFALSE; // use Kinematics filter
47 Bool_t      kUseMuonfilter     = kFALSE; // use Kinematics filter
48 TString     kCommonOutputFileName = "PWG4_JetTasksOutput.root";
49 TString     kCaloQAOutputFileName = "PWG4_CaloQAOutput.root";
50
51
52 //== general process variables
53
54 // ### Other flags to steer the analysis
55 //==============================================================================
56 Bool_t      kSkipTerminate      = kTRUE; // Do not call Teminate
57 Bool_t      kUseDate            = kFALSE; // use date in train name
58 Bool_t      kUseDebug           = kTRUE; // activate debugging
59 Int_t         kErrorIgnoreLevel = -1; // takes the errror print level from .rootrc 
60 // From TError.h:
61 // const Int_t kUnset    =  -1;
62 // const Int_t kPrint    =   0;
63 // const Int_t kInfo     =   1000;
64 // const Int_t kWarning  =   2000;
65 // const Int_t kError    =   3000;
66 // const Int_t kBreak    =   4000;
67 // const Int_t kSysError =   5000;
68 // const Int_t kFatal    =   6000; 
69 Int_t         kUseSysInfo         = 0; // activate debugging
70 Long64_t    kNumberOfEvents     = 1234567890; // number of events to process from the chain
71 Bool_t      kUseMC              = kTRUE;  // use MC info
72 Bool_t      kIsMC               = kTRUE;  // is MC info, if false it overwrites Use(AOD)MC
73 Bool_t      kUseAODMC           = kTRUE;  // use MC infA
74 Bool_t      kUseESDTags         = kFALSE; // use ESD tags for selection
75 Bool_t      kUseTR              = kFALSE;  // use track references
76 Bool_t      kUseAODTags         = kFALSE;  // use AOD tags
77 Bool_t      kSaveTrain          = kFALSE;  // save train configuration as: 
78 Bool_t      kIsPbPb             = kFALSE;  // Pb+Pb
79
80
81 // ### Analysis modules to be included. Some may not be yet fully implemented.
82 //==============================================================================
83 Int_t       iJETAN             = 1;      // Jet analysis (PWG4) // 1 write standard 2 write non-standard jets, 3 wrtie both
84 Int_t       iJETSUBTRACT        = 1;      // Jet background subtration
85 TList       kJetListSpectrum;             // list of jets contains TObjString of possible jet finder names
86 TExMap      kJetMapSpectrum;             // Maps the jet finder pairs to be used in the spectrum task second number negative no pair other wise (j1+1) + (1000 * (j2+1)) +10000 * (j3+1)
87 TExMap      kJetBackMapSpectrum;             // Maps the jet finder pairs with the background branch used, just for countint of trackrefs
88 Int_t       kJetMapOffset[3] = {10000,100,1};
89 TString     kDefaultJetBranch     = "";      // is currently set when filled (iJETAN or clusters) or from config macro 
90 TString     kDefaultJetBackgroundBranch            = "";      // is currently set when filled (jet clsuters  
91 TString     kDefaultJetBackgroundBranchCut1        = "";      // is currently set when filled (jet clsuters  
92 TString     kDefaultJetBackgroundBranch_extra     = "";      // is currently set when filled (jet clsuters) 
93 TString     kJetSubtractBranches     = "";      // is currently set when filled (jet clsuters  
94 TString     kJetSubtractBranchesCut1     = "";      // is currently set when filled (jet clsuters  
95 TString     kJetSubtractBranches_extra     = "";      // is currently set when filled (jet clsuters  
96
97 TString     kDefaultJetBranchMC     = "";      // is currently set when filled (iJETAN or clusters) or from config macro 
98 TString     kDefaultJetBackgroundBranchMC     = "";      // is currently set when filled (jet clsuters  
99 TString     kDefaultJetBranchMC2     = "";      // is currently set when filled (iJETAN or clusters) or from config macro 
100 TString     kDefaultJetBackgroundBranchMC2     = "";      // is currently set when filled (jet clsuters  
101 TString     kJetSubtractMask1 = "B0";
102 TString     kJetSubtractMask2 = "B%d";
103 Int_t       iDIJETAN           = 1;
104 Int_t       iJETANLib          = 1;
105 Int_t       iPWG1QASym         = 0;      // Eva's QA task compiled on the fly...
106 Int_t       iPWG4FastEmbedding = 0;      // Generate non-standard AOD for embedding
107 Int_t       iPWG4JetTasks      = 0;      // all jet tasks flag for lib laoding
108 Int_t       iPWG4JetServices   = 0;      // jet spectrum analysis
109 Int_t       iPWG4JetSpectrum   = 0;      // jet spectrum analysis
110 Int_t       iPWG4JetResponse   = 0;      // jet response matrix
111 Int_t       iPWG4JCORRAN       = 0;      // JCORRAN module
112 Int_t       iPWG4UE            = 0;      // Underlying Event analysis
113 Int_t       iPWG4LeadingUE     = 0;      // Underlying Event analysis
114 Int_t       iPWG4CorrectionsUE = 0;      // Underlying Event analysis
115 Int_t       iPWG4TmpSourceSara = 0;      // Underlying Event analysis not in svn
116 Int_t       iPWG4Fragmentation = 1;      // Official Fragmentation
117 Int_t       iPWG4JetChem       = 0;      // Jet chemistry 
118 Int_t       iPWG4PtQAMC        = 0;      // Marta's QA tasks 
119 Int_t       iPWG4PtTrackQA     = 0;      // Marta's QA tasks  
120 Int_t       iPWG4PtSpectra     = 0;      // Marta's QA tasks 
121 Int_t       iPWG4PtQATPC       = 0;      // Marta's QA tasks 
122 Int_t       iPWG4Cosmics     = 0;      // Marta's Cosmics Taks 
123 Int_t       iPWG4ThreeJets     = 0;      // Sona's thrust task
124 Int_t       iPWG4QGSep     = 0;          // Sona's QG Separation task
125 Int_t       iPWG4Minijet       = 0;      // Eva's Mini Jet Task cluster task 
126 Int_t       iPWG4KMeans        = 0;      // Andreas' KMeans task 
127 Int_t       iPWG4Cluster       = 0;      // CKB cluster task 
128 Int_t       iEMCUtilLibs       = 0;      // Flag to satisfy dependence on EMC utils
129 Int_t       iPWG4PartCorrLibs  = 0;      // Gustavo's part corr analysis
130 Int_t       iPWG4PartCorr      = 0;      // Gustavo's part corr analysis
131 Int_t       iPWG4CaloQA        = 0;      // Gustavo's part corr analysis
132 Int_t       iPWG4JetCorr       = 0;     // Paul's jet corr analysis
133 Int_t       iPWG4Tagged        = 0;      // Gustavo's part corr analysis
134 Int_t       iPWG4omega3pi      = 0;      // Omega to 3 pi analysis (PWG4) 
135 Int_t       iPWG4GammaConvLib     = 0;      // Gamma Conversio
136 Int_t       iPWG4GammaConv     = 0;      // Gamma Conversio
137 Int_t       iPWG4CaloConv     = 0;      // Gamma Conversio
138 Int_t       kHighPtFilterMask  = 32;     // change depending on the used AOD Filter
139 TString     kDeltaAODJetName   = "AliAOD.Jets.root";     
140 TString     kDeltaAODJetNameInput   = "";     
141 TString     kDeltaAODJCORRANName   = "AliAOD.JCORRAN.root";     
142 TString     kDeltaAODPartCorrName   = "AliAOD.PartCorr.root";     
143 TString     kFastEmbeddingAOD  = "emb/AliAOD.root";
144 TString     kFastEmbAODList    = "";
145
146 //==============================================================================
147 // ### PROOF Steering varibales
148 //==============================================================================
149 //== proof setup variables
150 TString     kProofCluster      = "alicecaf.cern.ch";
151 Bool_t      kProofUseAFPAR     = kFALSE;  // use AF special par file
152 TString     kProofAFversion          = "AF-v4-17";
153 //== proof input and output variables
154 TString     kProofDataSet      = "/COMMON/COMMON/LHC09a4_run8100X#/esdTree";
155 Bool_t      kProofSaveToAlien   = kFALSE; // save proof outputs in AliEn train_[trainName]_ddMonthyyyy_time.C
156 TString     kProofOutdir       = "";
157 Bool_t      kProofClearPackages = kFALSE;
158 Int_t       kProofEvents = 10000;
159 Int_t       kProofOffset = 0;
160 //== proof process variables
161
162
163 //==============================================================================
164 // ### Grid plugin Steering varibiables
165 //==============================================================================
166 //== grid plugin setup variables
167 Bool_t      kPluginUse         = kTRUE;   // do not change
168 Bool_t      kPluginUseProductionMode  = kFALSE;   // use the plugin in production mode
169 TString     kPluginRootVersion       = "v5-28-00c";  // *CHANGE ME IF MORE RECENT IN GRID*
170 TString     kPluginAliRootVersion    = "v4-21-01a-AN";  // *CHANGE ME IF MORE RECENT IN GRID*                                          
171 Bool_t      kPluginMergeViaJDL       = kTRUE;  // merge via JDL
172 Bool_t      kPluginFastReadOption   = kFALSE;  // use xrootd tweaks
173 Bool_t      kPluginOverwriteMode    = kTRUE;  // overwrite existing collections
174 Int_t       kPluginOutputToRunNumber = 1;     // write the output to subdirs named after run number
175 // TString kPluginExecutableCommand = "root -b -q";
176 TString     kPluginExecutableCommand = "source /Users/kleinb/setup_32bit_aliroot_trunk_clean_root_trunk.sh; alienroot -b -q ";
177
178 // == grid plugin input and output variables
179 TString     kGridDatadir      = "/alice/sim/PDC_08b/LHC09a1/AOD/";
180 Int_t         kGridMaxRunsFromList = 999999999;
181 Int_t         kGridOffsetRunFromList = 0; // skip the first n runs from the list
182 TString     kGridLocalRunList = "";
183 TString     kGridOutdir       = ""; // AliEn output directory. If blank will become output_<kTrainName>
184 TString     kGridDataSet      = ""; // sub working directory not to confuse different run xmls 
185 TString     kGridExtraAliendirLevel = ""; // sub working directory not to confuse different run xmls 
186 Int_t         kGridRunRange[2]       =  {0, -1}; // Set the run range
187 TString     kGridRunPattern        = "%03d"; // important for leading zeroes!!
188 TString     kGridPassPattern       = "";
189 TString     kGridExtraFiles        = ""; // files that will be added to the input list in the JDL...
190 Int_t         kGridMaxMergeFiles      = 25; // Number of files merged in a chunk grid run range
191 TString     kGridMergeExclude       = "AliAOD.root"; // Files that should not be merged
192 TString     kGridOutputStorages      = "disk=2"; // Make replicas on the storages
193 // == grid process variables
194 Int_t       kGridRunsPerMaster     = 100; // Number of runs per master job
195 Int_t       kGridFilesPerJob       = 100; // Maximum number of files per job (gives size of AOD)
196
197 //==============================================================================
198 // ### Local Steering variables
199 //==============================================================================
200 //== local setup variables
201 //== local input and output variables
202 TString     kLocalXMLDataset   = ""; // Change local xml dataset for local interactive analysis
203 TString     kLocalDataList   = "local_deltaaod.txt"; // Change local xml dataset for local interactive analysis
204 // == local process variables
205
206 TString kPluginMode = "";
207 TString kAnalysisMode = "";
208
209
210 // Temporaries.
211 TString anaPars = "";
212 TString anaLibs = "";
213 TString anaLibsExtra = "";
214 TString anaSources = "";
215 // Function signatures
216 class AliAnalysisAlien;
217 class AliAnalysisManager;
218
219 //______________________________________________________________________________
220 void AnalysisTrainPWG4Jets(const char *analysis_mode="local", 
221                            const char *plugin_mode="",
222                            const char *config_file="",Int_t iOffset = 0,Int_t iTotal = 0)
223 {
224 // Main analysis train macro. If a configuration file is provided, all parameters
225 // are taken from there but may be altered by CheckModuleFlags.
226
227   // these flag may be needed by the config file
228   kPluginMode   = plugin_mode;
229   kAnalysisMode = analysis_mode;
230   
231   if (strlen(config_file) && !LoadConfig(config_file)) return;
232   if(iTotal>0)kGridMaxRunsFromList = iTotal; // overwrites the settings from config file
233   if(iOffset)kGridOffsetRunFromList = iOffset;
234   if(iOffset)kProofOffset = iOffset;
235
236
237    TString smode(analysis_mode);
238    smode.ToUpper();
239    if (kSaveTrain)WriteConfig();
240    // Check compatibility of selected modules 
241    CheckModuleFlags(smode);
242    //     gROOT->ProcessLine(".trace");
243
244    printf("==================================================================\n");
245    printf("===========    RUNNING ANALYSIS TRAIN %s IN %s MODE   ==========\n", kTrainName.Data(),smode.Data());
246    printf("==================================================================\n");
247                               printf("=  Configuring analysis train for:                               =\n");
248    if (iAODanalysis) printf("=  AOD analysis                                                  =\n");
249    else                     printf("=  ESD analysis                                                  =\n");
250    if (iPhysicsSelection)   printf("=  Physics selection                                                =\n");
251    if(iCentralitySelection)printf("=  Centrality selection                                                =\n");
252    if (useTender)   printf("=  Using tender                                                =\n");
253    if (iESDfilter)   printf("=  ESD filter                                                    =\n");
254    if (iJETAN)       printf("=  Jet analysis                                                  =\n");
255    printf("==================================================================\n");
256
257    char *printMask = ":: %20s  %10d\n";
258    printf(printMask,"Fill AOD",(UInt_t)kFillAOD);
259    printf(printMask,"Save AOD", (UInt_t)kSaveAOD);
260    printf(printMask,"MC truth", (UInt_t)kUseMC);
261    printf(printMask,"KINE filter", (UInt_t)kUseKinefilter);
262    printf(printMask,"track refs", (UInt_t)kUseTR);
263    printf(printMask,"tags", (UInt_t)kUseESDTags);
264    printf(printMask,"AOD tags", (UInt_t)kUseAODTags);
265    printf(printMask,"debugging", (UInt_t)kUseDebug);
266    printf(printMask,"PAR files", (UInt_t)kUsePAR);
267    printf(printMask,"AliEn plugin", (UInt_t)kPluginUse);
268    printf(printMask,"JETAN subtract", (UInt_t)iJETSUBTRACT);
269    printf(printMask,"PWG1 QA sym", iPWG1QASym);
270    printf(printMask,"PWG4 Source Sara",iPWG4TmpSourceSara);
271    printf(printMask,"PWG4 Fragmentation",iPWG4Fragmentation);
272    printf(printMask,"PWG4 Jet Chem",iPWG4JetChem);
273    printf(printMask,"PWG4 Jet tasks",iPWG4JetTasks);
274    printf(printMask,"PWG4 Jet Services",iPWG4JetServices);     
275    printf(printMask,"PWG4 Jet Spectrum",iPWG4JetSpectrum);
276    printf(printMask,"PWG4 JCORRAN",iPWG4JCORRAN);
277    printf(printMask,"PWG4 UE",iPWG4UE); 
278    printf(printMask,"PWG4 Leading UE",iPWG4LeadingUE); 
279    printf(printMask,"PWG4 Corrections UE",iPWG4CorrectionsUE); 
280    printf(printMask,"PWG4 Pt QA MC",iPWG4PtQAMC);
281    printf(printMask,"PWG4 Pt QA track",iPWG4PtTrackQA);
282    printf(printMask,"PWG4 Pt Spectra",iPWG4PtSpectra);
283    printf(printMask,"PWG4 Pt QA TPC",iPWG4PtQATPC);     
284    printf(printMask,"PWG4 Cosmics",iPWG4Cosmics);     
285    printf(printMask,"PWG4 Three Jets",iPWG4ThreeJets);
286    printf(printMask,"PWG4 QGSep",iPWG4QGSep);
287    printf(printMask,"PWG4 Minijet",iPWG4Minijet);
288    printf(printMask,"PWG4 KMeans",iPWG4KMeans);
289    printf(printMask,"PWG4 Cluster",iPWG4Cluster);
290    printf(printMask,"PWG4 Part Corr",iPWG4PartCorr);
291    printf(printMask,"PWG4 Calo QA",iPWG4CaloQA);
292    printf(printMask,"PWG4 Jet Corr",iPWG4JetCorr);
293    printf(printMask,"PWG4 JCORRAN",iPWG4JCORRAN);
294    printf(printMask,"PWG4 Tagged",iPWG4Tagged);
295    printf(printMask,"PWG4 omega to 3 pi ",iPWG4omega3pi);
296    printf(printMask,"PWG4 Gamma Conv",iPWG4GammaConv);
297    printf(printMask,"PWG4 Calo Conv",iPWG4CaloConv);
298    printf(printMask,"HighPt FilterMask",kHighPtFilterMask);    
299    
300    //==========================================================================
301    // Connect to back-end system
302    if (!Connect(smode)) {
303       ::Error("AnalysisTrain", "Could not connect to %s back-end", analysis_mode);
304       return;
305    }   
306
307    // Load common libraries and set include path
308    if (!LoadCommonLibraries(smode)) {
309       ::Error("AnalysisTrain", "Could not load common libraries");
310       return;
311    }
312
313
314     
315    // Make the analysis manager and connect event handlers
316    AliAnalysisManager *mgr  = new AliAnalysisManager("PWG4Train", "pwg4 mini train");
317    if (kCommonOutputFileName.Length()>0)mgr->SetCommonFileName(kCommonOutputFileName.Data());
318    if (kProofSaveToAlien) mgr->SetSpecialOutputLocation(kProofOutdir);
319    mgr->SetNSysInfo(0);
320    if (!strcmp(plugin_mode, "test")) mgr->SetNSysInfo(1);
321    if (kUseSysInfo)mgr->SetNSysInfo(kUseSysInfo);
322    mgr->SetSkipTerminate(kSkipTerminate);
323
324    // Load analysis specific libraries
325    if (!LoadAnalysisLibraries(smode)) {
326       ::Error("AnalysisTrain", "Could not load analysis libraries");
327      return;
328    }   
329
330    // Create input handler (input container created automatically)
331    if (iAODanalysis) {
332    // AOD input handler
333       AliAODInputHandler *aodH = new AliAODInputHandler();
334       mgr->SetInputEventHandler(aodH);
335       if (kDeltaAODJetNameInput.Length()){
336         Printf("Adding Friend %s",kDeltaAODJetNameInput.Data());
337         aodH->AddFriend(kDeltaAODJetNameInput.Data());
338       }
339       //      if (iPWG4PartCorr) aodH->AddFriend(Form("deltas/%s"kDeltaAODJetName.Data()));
340    } else {   
341    // ESD input handler
342       AliESDInputHandler *esdHandler = new AliESDInputHandler();
343       if (kUseESDTags) esdHandler->SetReadTags();
344       esdHandler->SetReadFriends(kFALSE);
345       mgr->SetInputEventHandler(esdHandler);       
346       //      if(iPWG4PtQATPC&& !kTrainName.Contains("pass5"))esdHandler->SetActiveBranches("ESDfriend");
347
348    }
349
350    // Monte Carlo handler
351    if (kUseMC && !iAODanalysis) {
352       AliMCEventHandler* mcHandler = new AliMCEventHandler();
353       mgr->SetMCtruthEventHandler(mcHandler);
354       mcHandler->SetReadTR(kUseTR); 
355    }   
356    // AOD output container, created automatically when setting an AOD handler
357    if (iAODhandler) {
358       // AOD output handler
359       AliAODHandler* aodHandler   = new AliAODHandler();
360       aodHandler->SetOutputFileName("AliAOD.root");
361       aodHandler->SetFillAODforRun(kFillAOD);
362       //
363       mgr->SetOutputEventHandler(aodHandler);
364       AliAnalysisDataContainer * cout_aod = mgr->GetCommonOutputContainer();
365       cout_aod->SetSpecialOutput();
366    }
367    // Debugging if needed
368
369    if (kUseDebug){
370      mgr->SetDebugLevel(3);
371    }
372    if(kUseSysInfo>0){
373      mgr->RegisterExtraFile("syswatch.root");
374      if(kGridMergeExclude.Length())kGridMergeExclude += " ";
375      kGridMergeExclude += "syswatch.root";
376    }
377    else{
378      AliLog::SetGlobalLogLevel(AliLog::kError);
379    }
380
381
382    //==========================================================================
383    // Create the chain. In this example it is created only from ALIEN files but
384    // can be done to work in batch or grid mode as well.
385    TChain *chain = CreateChain(smode, plugin_mode);
386         
387    //==========================================================================
388    // Load the tasks configuration macros for all wagons. These files are supposed now to be
389    // in the current workdir, but in AliEn they will be in the file catalog, 
390    // mapped from AliRoot and pecified in the jdl input list.
391     
392    // For now connection to top input container and common AOD output container
393    // is done in this macro, but in future these containers will be connected
394    // from each task configuration macro.
395    
396    //                                                                                                                              
397    // Tender and supplies. Needs to be called for every event.                                                                     
398    //                                                                                                                              
399
400    if (useTender) {
401       gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/TenderSupplies/AddTaskTender.C");
402       AliAnalysisTaskSE *tender = AddTaskTender(kTRUE);
403       //      tender->SelectCollisionCandidates();                                                                                      
404       tender->SetDebugLevel(2);
405    }
406
407    
408    Float_t fTrackEtaWindow = 0.9;
409    Float_t fJetEtaWindow   = 0.5;
410
411    /*
412    if(kIsPbPb){// for pass1
413      Float_t fTrackEtaWindow = 0.8;
414      Float_t fJetEtaWindow   = 0.4;
415    }
416    */
417
418
419    if(iPhysicsSelection && !iAODanalysis){
420      gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPhysicsSelection.C");
421      Int_t iTriggerHIC = 0;
422      Bool_t rejectBkg = true;
423      if(kIsPbPb){
424        iTriggerHIC = 2;
425        rejectBkg = false; // for the moment...
426      }
427      AliPhysicsSelectionTask* physSelTask = AddTaskPhysicsSelection(kIsMC,rejectBkg);  
428
429      mgr->RegisterExtraFile("EventStat_temp.root");
430      mgr->AddStatisticsTask();
431    }
432    else{
433      iPhysicsSelectionFlag = AliVEvent::kMB;
434    }
435
436    if(iCentralitySelection){
437
438      // has to run before AOD filter
439      gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskCentrality.C");
440      //     const char* file1="$ALICE_ROOT/ANALYSIS/macros/AliCentralityBy1D_137161.root";
441      //     const char* file2="$ALICE_ROOT/ANALYSIS/macros/AliCentralityByFunction_137161.root";
442      AliCentralitySelectionTask *taskC = AddTaskCentrality();
443       if (!taskC) ::Warning("AnalysisTrainPWG4Jets", "AliCentralitySelectionTask cannot run for this train conditions - EXCLUDED");
444    }
445
446    if (iESDfilter && !iAODanalysis) {
447       //  ESD filter task configuration.
448       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskESDFilterPWG4Train.C");
449       AliAnalysisTaskESDfilter *taskesdfilter = AddTaskESDFilter(kUseKinefilter,kUseMuonfilter);
450       taskesdfilter->SetEnableFillAOD(!kFilterAOD);
451       taskesdfilter->DisableV0s();
452       taskesdfilter->DisableCascades();
453       taskesdfilter->DisableKinks();
454       taskesdfilter->DisablePmdClusters();
455       taskesdfilter->DisableCaloClusters();
456       taskesdfilter->DisableCells();
457
458       if(kIsMC){
459         mgr->RegisterExtraFile("pyxsec_hists.root");
460         if(kGridMergeExclude.Length())kGridMergeExclude += " ";
461         kGridMergeExclude += "pyxsec_hists.root";
462
463       }
464    }   
465
466    // AOD tags
467    if (kUseAODTags) {
468       AliAnalysisTaskTagCreator* tagTask = new AliAnalysisTaskTagCreator("AOD Tag Creator");
469       mgr->AddTask(tagTask);
470       AliAnalysisDataContainer *coutTags = mgr->CreateContainer("cTag",  TTree::Class(), 
471                                            AliAnalysisManager::kOutputContainer, "AOD.tag.root");
472       mgr->ConnectInput (tagTask, 0, mgr->GetCommonInputContainer());
473       mgr->ConnectOutput(tagTask, 1, coutTags);
474    }   
475
476    if (iPWG4FastEmbedding) {
477      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskFastEmbedding.C");
478      AliAnalysisTaskFastEmbedding *taskEmbedding = 0;
479      if(kFastEmbAODList.Length()) taskEmbedding = AddTaskFastEmbedding(kFastEmbAODList, 1);
480      else                         taskEmbedding = AddTaskFastEmbedding(kFastEmbeddingAOD, 0);
481      taskEmbedding->SetJetBranch("jetsAOD_UA104_B0_Filter00256_Cut01000");
482      // taskEmbedding->SetEvtSelecMode(AliAnalysisTaskFastEmbedding::kEventsAll);
483      // taskEmbedding->SetDebugLevel(10);
484    }
485
486     // Jet analysis
487    if (iJETAN) {
488       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJets.C");
489       AliAnalysisTaskJets *taskjets = 0;
490       if(iJETAN&1){
491         /*
492         taskjets = AddTaskJets(kHighPtFilterMask); 
493         taskjets->SetName("StandardJets");
494         taskjets->SetNonStdBranch("");
495         */
496       }
497       if(iJETAN&2){
498         // Set only few jet finders  backgroudn subtraction w an wo 
499         
500         taskjets = AddTaskJets("AOD","UA1",0.4,kHighPtFilterMask,1.,0); // no background subtraction
501         if(kDeltaAODJetName.Length()>0)taskjets->SetNonStdOutputFile(kDeltaAODJetName.Data());
502         TString cTmp("");       
503         cTmp = taskjets->GetNonStdBranch();
504         if(cTmp.Length())kJetListSpectrum.Add(new TObjString(cTmp.Data()));
505
506         taskjets = AddTaskJets("AOD","UA1",0.4,kHighPtFilterMask,2.,0); // no background subtraction
507         if(kDeltaAODJetName.Length()>0)taskjets->SetNonStdOutputFile(kDeltaAODJetName.Data());
508         TString cTmp("");       
509         cTmp = taskjets->GetNonStdBranch();
510         if(cTmp.Length())kJetListSpectrum.Add(new TObjString(cTmp.Data()));
511
512
513         // STANDARD UA jet finders pT cut 1 GeV background mode 2 R = 0.4
514         if(kIsPbPb){
515           taskjets = AddTaskJets("AOD","UA1",0.4,kHighPtFilterMask,1.,2); // background subtraction
516           if(kDeltaAODJetName.Length()>0)taskjets->SetNonStdOutputFile(kDeltaAODJetName.Data());
517           cTmp = taskjets->GetNonStdBranch();
518           if(cTmp.Length())kJetListSpectrum.Add(new TObjString(cTmp.Data()));
519           taskjets = AddTaskJets("AOD","UA1",0.4,kHighPtFilterMask,2.,2); // background subtraction
520           if(kDeltaAODJetName.Length()>0)taskjets->SetNonStdOutputFile(kDeltaAODJetName.Data());
521           cTmp = taskjets->GetNonStdBranch();
522           if(cTmp.Length())kJetListSpectrum.Add(new TObjString(cTmp.Data()));
523         }
524
525
526
527         // SICONE 
528         taskjets = AddTaskJets("AOD","SISCONE",0.4,kHighPtFilterMask,0.15,0); //no background subtraction to be done later....
529         if(kDeltaAODJetName.Length()>0)taskjets->SetNonStdOutputFile(kDeltaAODJetName.Data());
530         cTmp = taskjets->GetNonStdBranch();
531         if(cTmp.Length()>0)kJetSubtractBranches += Form("%s ",cTmp.Data());
532         if(cTmp.Length())kJetListSpectrum.Add(new TObjString(cTmp.Data()));
533
534         if(kUseAODMC){
535           // STANDARD UA jet finders pT cut 1 GeV background mode 2 R = 0.4
536           if(kIsPbPb){
537             taskjets = AddTaskJets("AODMC","UA1",0.4,kHighPtFilterMask,1.,2); // background subtraction
538             cTmp = taskjets->GetNonStdBranch();
539             if(cTmp.Length())kJetListSpectrum.Add(new TObjString(cTmp.Data()));
540             taskjets = AddTaskJets("AODMC2","UA1",0.4,kHighPtFilterMask,1.,2); // background subtraction
541             cTmp = taskjets->GetNonStdBranch();
542             if(cTmp.Length())kJetListSpectrum.Add(new TObjString(cTmp.Data()));
543           }
544           else{
545             taskjets = AddTaskJets("AODMC","UA1",0.4,kHighPtFilterMask,1.,0); // no background subtraction
546             cTmp = taskjets->GetNonStdBranch();
547             if(cTmp.Length())kJetListSpectrum.Add(new TObjString(cTmp.Data()));
548             taskjets = AddTaskJets("AODMC2","UA1",0.4,kHighPtFilterMask,1.,0); // no background subtraction
549             cTmp = taskjets->GetNonStdBranch();
550             if(cTmp.Length())kJetListSpectrum.Add(new TObjString(cTmp.Data()));
551           }
552         }
553         if(kDeltaAODJetName.Length()>0)mgr->RegisterExtraFile(kDeltaAODJetName.Data()); 
554       }
555       if (!taskjets) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJets cannot run for this train conditions - EXCLUDED");
556    }
557
558
559    if (iPWG4FastEmbedding && iJETAN) {
560      AliAnalysisTaskJets *taskEmbJets = AddTaskJets("AODextra", "FASTJET", 0.4, kHighPtFilterMask);
561      taskEmbJets->ReadAODFromOutput();
562      kJetSubtractBranches_extra += Form("%s ", taskEmbJets->GetNonStdBranch());
563
564      taskEmbJets = AddTaskJets("AODextraonly", "FASTJET", 0.4, kHighPtFilterMask);
565      taskEmbJets->ReadAODFromOutput();
566     
567      taskEmbJets = AddTaskJets("AODextra", "UA1", 0.4, kHighPtFilterMask,1.,0);
568      taskEmbJets->ReadAODFromOutput();
569      taskEmbJets = AddTaskJets("AODextraonly", "UA1", 0.4, kHighPtFilterMask,1.,0);
570      taskEmbJets->ReadAODFromOutput();
571      taskEmbJets = AddTaskJets("AODextra", "UA1", 0.4, kHighPtFilterMask,1.,2);
572      taskEmbJets->ReadAODFromOutput();
573    }
574
575    if(iPWG4Cluster){
576      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetCluster.C");
577      AliAnalysisTaskJetCluster *taskCl = 0;
578      Float_t fCenUp = 0;
579      Float_t fCenLo = 0;
580      if(kIsPbPb&&!kIsMC){
581        fCenLo = 0;
582        fCenUp = 80;
583      }
584      if(iPWG4Cluster&1){
585
586        if(kIsPbPb){
587          taskCl = AddTaskJetCluster("AOD","",kHighPtFilterMask,iPhysicsSelectionFlag,"KT",0.4,0,1, kDeltaAODJetName.Data(),0.15,fTrackEtaWindow,0); // this one is for the background and random jets, random cones with no skip
588          taskCl->SetBackgroundCalc(kTRUE);
589          taskCl->SetNRandomCones(1);
590          //      taskCl->SetDebugLevel(11);
591          taskCl->SetCentralityCut(fCenLo,fCenUp);
592          taskCl->SetGhostEtamax(fTrackEtaWindow);
593          kDefaultJetBackgroundBranch = Form("%s_%s",AliAODJetEventBackground::StdBranchName(),taskCl->GetJetOutputBranch());
594          kJetListSpectrum.Add(new TObjString(taskCl->GetJetOutputBranch()));
595          kJetListSpectrum.Add(new TObjString(Form("%sRandomConeSkip%02d",taskCl->GetJetOutputBranch(),0)));
596          kJetListSpectrum.Add(new TObjString(Form("%sRandomCone_random",taskCl->GetJetOutputBranch())));
597
598          taskCl = AddTaskJetCluster("AOD","",kHighPtFilterMask,iPhysicsSelectionFlag,"KT",0.4,0,1, kDeltaAODJetName.Data(),2.0,fTrackEtaWindow,0); // this one is for the background and random jets, random cones with no skip
599          taskCl->SetNRandomCones(1);
600          taskCl->SetBackgroundCalc(kTRUE);
601          taskCl->SetCentralityCut(fCenLo,fCenUp);
602          taskCl->SetGhostEtamax(fTrackEtaWindow);
603          if(iAODanalysis==2)taskCl->SetAODTrackInput(kTRUE);
604          kDefaultJetBackgroundBranchCut1 = Form("%s_%s",AliAODJetEventBackground::StdBranchName(),taskCl->GetJetOutputBranch());
605          kJetListSpectrum.Add(new TObjString(taskCl->GetJetOutputBranch()));
606          kJetListSpectrum.Add(new TObjString(Form("%sRandomConeSkip%02d",taskCl->GetJetOutputBranch(),0)));
607          kJetListSpectrum.Add(new TObjString(Form("%sRandomCone_random",taskCl->GetJetOutputBranch())));
608
609          if (iPWG4FastEmbedding) {
610            AliAnalysisTaskJetCluster *taskClEmb = 0;
611            taskClEmb = AddTaskJetCluster("AODextra","",kHighPtFilterMask,iPhysicsSelectionFlag,"KT",0.4,0,1, kDeltaAODJetName.Data(),0.15,fTrackEtaWindow); // this one is for the background and random jets
612            taskClEmb->SetBackgroundCalc(kTRUE);
613            taskClEmb->SetCentralityCut(fCenLo,fCenUp);
614            taskClEmb->SetGhostEtamax(fTrackEtaWindow);
615            if(iAODanalysis==2)taskClEmb->SetAODTrackInput(kTRUE);
616            kDefaultJetBackgroundBranch_extra = Form("%s_%s",AliAODJetEventBackground::StdBranchName(),taskClEmb->GetJetOutputBranch());
617
618            taskClEmb = AddTaskJetCluster("AODextraonly","",kHighPtFilterMask,iPhysicsSelectionFlag,"KT",0.4,0,1, kDeltaAODJetName.Data(),0.15,fTrackEtaWindow); // this one is for the background and random jets
619            taskClEmb->SetBackgroundCalc(kFALSE);
620            taskClEmb->SetCentralityCut(fCenLo,fCenUp);
621            taskClEmb->SetGhostEtamax(fTrackEtaWindow);
622            if(iAODanalysis==2)taskClEmb->SetAODTrackInput(kTRUE);
623            
624            taskClEmb = AddTaskJetCluster("AODextra","",kHighPtFilterMask,iPhysicsSelectionFlag,"ANTIKT",0.4,0,1,kDeltaAODJetName.Data(),0.15,fTrackEtaWindow);
625            taskClEmb->SetCentralityCut(fCenLo,fCenUp);
626            taskClEmb->SetBackgroundBranch(kDefaultJetBackgroundBranch_extra.Data());
627            kJetSubtractBranches_extra += Form("%s ",taskClEmb->GetJetOutputBranch());
628            if(iAODanalysis==2)taskClEmb->SetAODTrackInput(kTRUE);
629
630            taskClEmb = AddTaskJetCluster("AODextraonly","",kHighPtFilterMask,iPhysicsSelectionFlag,"ANTIKT",0.4,0,1,kDeltaAODJetName.Data(),0.15,fTrackEtaWindow);
631            taskClEmb->SetCentralityCut(fCenLo,fCenUp);
632            if(iAODanalysis==2)taskClEmb->SetAODTrackInput(kTRUE);
633          }
634
635          taskCl = AddTaskJetCluster("AOD","",kHighPtFilterMask,iPhysicsSelectionFlag,"KT",0.2,0,1, kDeltaAODJetName.Data(),0.15); // this one is for the background and random jets
636          taskCl->SetBackgroundCalc(kTRUE);
637          taskCl->SetCentralityCut(fCenLo,fCenUp);
638          taskCl->SetGhostEtamax(fTrackEtaWindow);
639          kJetListSpectrum.Add(new TObjString(taskCl->GetJetOutputBranch()));
640          if(iAODanalysis==2)taskCl->SetAODTrackInput(kTRUE);
641        }
642        else{
643          taskCl = AddTaskJetCluster("AOD","",kHighPtFilterMask,iPhysicsSelectionFlag,"KT",0.6,0,1,kDeltaAODJetName.Data(),0.15); // this one is for the background jets
644          taskCl->SetBackgroundCalc(kTRUE);
645          kDefaultJetBackgroundBranch = Form("%s_%s",AliAODJetEventBackground::StdBranchName(),taskCl->GetJetOutputBranch());
646          taskCl->SetGhostEtamax(fTrackEtaWindow);
647          if(iAODanalysis==2)taskCl->SetAODTrackInput(kTRUE);
648          kJetListSpectrum.Add(new TObjString(taskCl->GetJetOutputBranch()));
649
650          taskCl = AddTaskJetCluster("AOD","",kHighPtFilterMask,iPhysicsSelectionFlag,"KT",0.4,0,1,kDeltaAODJetName.Data(),0.15); 
651          taskCl->SetBackgroundCalc(kTRUE);
652          taskCl->SetGhostEtamax(fTrackEtaWindow);
653          if(iAODanalysis==2)taskCl->SetAODTrackInput(kTRUE);
654          kJetListSpectrum.Add(new TObjString(taskCl->GetJetOutputBranch()));
655        } 
656
657        taskCl = AddTaskJetCluster("AOD","",kHighPtFilterMask,iPhysicsSelectionFlag,"ANTIKT",0.4,2,1,kDeltaAODJetName.Data(),0.15);
658        taskCl->SetCentralityCut(fCenLo,fCenUp);
659        if(kIsPbPb)taskCl->SetBackgroundBranch(kDefaultJetBackgroundBranch.Data());
660        taskCl->SetCentralityCut(fCenLo,fCenUp);
661        //       taskCl->SetDebugLevel(3);
662  
663        taskCl->SetNRandomCones(1);
664        if(iAODanalysis==2)taskCl->SetAODTrackInput(kTRUE);
665        kDefaultJetBranch = taskCl->GetJetOutputBranch();
666        kJetSubtractBranches += Form("%s ",taskCl->GetJetOutputBranch());
667        kJetListSpectrum.Add(new TObjString(taskCl->GetJetOutputBranch()));
668        kJetListSpectrum.Add(new TObjString(Form("%sRandomConeSkip%02d",taskCl->GetJetOutputBranch(),2)));
669        kJetListSpectrum.Add(new TObjString(Form("%sRandomCone_random",taskCl->GetJetOutputBranch())));
670
671        taskCl = AddTaskJetCluster("AOD","",kHighPtFilterMask,iPhysicsSelectionFlag,"ANTIKT",0.4,2,1,kDeltaAODJetName.Data(),2.0);
672        taskCl->SetCentralityCut(fCenLo,fCenUp);
673        if(iAODanalysis==2)taskCl->SetAODTrackInput(kTRUE);
674        if(kIsPbPb)taskCl->SetBackgroundBranch(kDefaultJetBackgroundBranchCut1.Data());
675        kJetSubtractBranchesCut1 += Form("%s ",taskCl->GetJetOutputBranch());
676        kJetListSpectrum.Add(new TObjString(taskCl->GetJetOutputBranch()));
677        
678
679        taskCl = AddTaskJetCluster("AOD","",kHighPtFilterMask,iPhysicsSelectionFlag,"ANTIKT",0.2,0,1,kDeltaAODJetName.Data(),0.15);
680        taskCl->SetCentralityCut(fCenLo,fCenUp);
681        if(iAODanalysis==2)taskCl->SetAODTrackInput(kTRUE);
682        if(kIsPbPb)taskCl->SetBackgroundBranch(kDefaultJetBackgroundBranch.Data());
683        kJetSubtractBranches += Form("%s ",taskCl->GetJetOutputBranch());
684        kJetListSpectrum.Add(new TObjString(taskCl->GetJetOutputBranch()));
685
686
687        if(kDeltaAODJetName.Length()==0&&kFilterAOD){
688          if(kIsPbPb)taskCl->SetJetTriggerPtCut(0.0001);
689          else taskCl->SetJetTriggerPtCut(20.);
690        }
691
692        if(kUseAODMC){
693          if(kIsPbPb){
694            taskCl = AddTaskJetCluster("AODMC","",kHighPtFilterMask,iPhysicsSelectionFlag,"KT",0.4,0,1, kDeltaAODJetName.Data(),0.15,fTrackEtaWindow); // this one is for the background and random jets
695            taskCl->SetBackgroundCalc(kTRUE);
696            taskCl->SetGhostEtamax(0.9);
697            kDefaultJetBackgroundBranchMC = Form("%s_%s",AliAODJetEventBackground::StdBranchName(),taskCl->GetJetOutputBranch());
698            if(iAODanalysis==2)taskCl->SetAODTrackInput(kTRUE);     
699          kJetListSpectrum.Add(new TObjString(taskCl->GetJetOutputBranch()));
700
701            taskCl = AddTaskJetCluster("AODMC2","",kHighPtFilterMask,iPhysicsSelectionFlag,"KT",0.4,0,1, kDeltaAODJetName.Data(),0.15); // this one is for the background and random jets
702            taskCl->SetBackgroundCalc(kTRUE);
703            taskCl->SetGhostEtamax(fTrackEtaWindow);
704            kDefaultJetBackgroundBranchMC2 = Form("%s_%s",AliAODJetEventBackground::StdBranchName(),taskCl->GetJetOutputBranch(),fTrackEtaWindow); 
705            if(iAODanalysis==2)taskCl->SetAODTrackInput(kTRUE);
706            kJetListSpectrum.Add(new TObjString(taskCl->GetJetOutputBranch()));
707          }
708          else{
709            taskCl = AddTaskJetCluster("AODMC","",kHighPtFilterMask,iPhysicsSelectionFlag,"KT",0.6,0,1, kDeltaAODJetName.Data(),0.15,fTrackEtaWindow); // this one is for the background and random jets
710            taskCl->SetBackgroundCalc(kTRUE);
711            taskCl->SetGhostEtamax(fTrackEtaWindow);
712            kDefaultJetBackgroundBranchMC = Form("%s_%s",AliAODJetEventBackground::StdBranchName(),taskCl->GetJetOutputBranch());
713          kJetListSpectrum.Add(new TObjString(taskCl->GetJetOutputBranch()));       
714
715            taskCl = AddTaskJetCluster("AODMC2","",kHighPtFilterMask,iPhysicsSelectionFlag,"KT",0.6,0,1, kDeltaAODJetName.Data(),0.15,fTrackEtaWindow); // this one is for the background and random jets
716            taskCl->SetBackgroundCalc(kTRUE);
717            taskCl->SetGhostEtamax(fTrackEtaWindow);
718            kDefaultJetBackgroundBranchMC2 = Form("%s_%s",AliAODJetEventBackground::StdBranchName(),taskCl->GetJetOutputBranch()); 
719            if(iAODanalysis==2)taskCl->SetAODTrackInput(kTRUE);
720            kJetListSpectrum.Add(new TObjString(taskCl->GetJetOutputBranch()));
721            // pp background calcs...
722          }
723          
724          taskCl = AddTaskJetCluster("AODMC","",kHighPtFilterMask,iPhysicsSelectionFlag,"ANTIKT",0.4,0,1, kDeltaAODJetName.Data(),0.15,fTrackEtaWindow); 
725          taskCl->SetGhostEtamax(fTrackEtaWindow);
726          if(kIsPbPb)taskCl->SetBackgroundBranch(kDefaultJetBackgroundBranchMC.Data());   
727          kDefaultJetBranchMC = taskCl->GetJetOutputBranch();
728          if(iAODanalysis==2)taskCl->SetAODTrackInput(kTRUE);
729          kJetListSpectrum.Add(new TObjString(taskCl->GetJetOutputBranch()));
730
731          taskCl = AddTaskJetCluster("AODMC2","",kHighPtFilterMask,iPhysicsSelectionFlag,"ANTIKT",0.4,0,1, kDeltaAODJetName.Data(),0.15,fTrackEtaWindow);
732          if(kIsPbPb)taskCl->SetBackgroundBranch(kDefaultJetBackgroundBranchMC2.Data());  
733          kDefaultJetBranchMC2 = taskCl->GetJetOutputBranch();
734          if(iAODanalysis==2)taskCl->SetAODTrackInput(kTRUE);
735          kJetListSpectrum.Add(new TObjString(taskCl->GetJetOutputBranch()));
736        }
737        
738        
739        if (!taskCl) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskCluster cannot run for this train conditions - EXCLUDED");
740      }
741    }
742
743
744    if(iJETSUBTRACT&&kJetSubtractBranches.Length()){
745      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetBackgroundSubtract.C");
746      AliAnalysisTaskJetBackgroundSubtract *taskSubtract = 0;
747      if(kJetSubtractBranches.Length()){
748
749
750
751
752        for(int iB = 1;iB<3;iB++){
753          if(iB>2)continue;
754          taskSubtract = AddTaskJetBackgroundSubtract(kJetSubtractBranches,iB,kJetSubtractMask1.Data(),kJetSubtractMask2.Data());
755          taskSubtract->SetBackgroundBranch(kDefaultJetBackgroundBranch.Data());         taskSubtract->SelectCollisionCandidates(iPhysicsSelectionFlag);
756          if(kDeltaAODJetName.Length()>0)taskSubtract->SetNonStdOutputFile(kDeltaAODJetName.Data());
757          //      taskSubtract->SetDebugLevel(10);
758          TString cTmp;       
759          TObjArray *objArr = kJetSubtractBranches.Tokenize(" ");
760          for(int iJB = 0;iJB<objArr->GetEntries();iJB++){
761            TObjString *ostr = (TObjString*)objArr->At(iJB);
762            cTmp = ostr->GetString().Data();
763            cTmp.ReplaceAll(kJetSubtractMask1.Data(),Form(kJetSubtractMask2.Data(),iB));
764            kJetListSpectrum.Add(new TObjString(cTmp.Data()));
765          }
766          
767          //     taskSubtract->SetDebugLevel(3);
768          if(iB==2){
769            if(kJetSubtractBranches.Contains(kDefaultJetBranch.Data())&&kIsPbPb){
770              kDefaultJetBranch.ReplaceAll(taskSubtract->GetToReplace(),Form(taskSubtract->GetReplacementMask(),taskSubtract->GetSubtractionMethod()));
771            }
772          }
773          
774        }
775
776        //
777        // cut1
778        Int_t iB = 2;
779        taskSubtract = AddTaskJetBackgroundSubtract(kJetSubtractBranchesCut1,iB,kJetSubtractMask1.Data(),kJetSubtractMask2.Data(),"Cut2000");
780        taskSubtract->SetBackgroundBranch(kDefaultJetBackgroundBranchCut1.Data());               
781        taskSubtract->SelectCollisionCandidates(iPhysicsSelectionFlag);
782        if(kDeltaAODJetName.Length()>0)taskSubtract->SetNonStdOutputFile(kDeltaAODJetName.Data());
783
784        objArr = kJetSubtractBranchesCut1.Tokenize(" ");
785        for(int iJB = 0;iJB<objArr->GetEntries();iJB++){
786          TObjString *ostr = (TObjString*)objArr->At(iJB);
787          cTmp = ostr->GetString().Data();
788          cTmp.ReplaceAll(kJetSubtractMask1.Data(),Form(kJetSubtractMask2.Data(),iB));
789          kJetListSpectrum.Add(new TObjString(cTmp.Data()));
790        }
791
792
793      }
794      if(kJetSubtractBranches_extra.Length()){
795        taskSubtract = AddTaskJetBackgroundSubtract(kJetSubtractBranches_extra,2,kJetSubtractMask1.Data(),kJetSubtractMask2.Data(),"extra");
796        taskSubtract->SetBackgroundBranch(kDefaultJetBackgroundBranch_extra.Data());
797        taskSubtract->SelectCollisionCandidates(iPhysicsSelectionFlag);
798        //taskSubtract->SetDebugLevel(3);
799        if(kDeltaAODJetName.Length()>0)taskSubtract->SetNonStdOutputFile(kDeltaAODJetName.Data());
800        if(kJetSubtractBranches_extra.Contains(kDefaultJetBranch.Data())){
801          kDefaultJetBranch.ReplaceAll(taskSubtract->GetToReplace(),Form(taskSubtract->GetReplacementMask(),taskSubtract->GetSubtractionMethod()));
802        }
803      }
804      if (!taskSubtract) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJetBackgroundSubtrac cannot run for this train conditions - EXCLUDED");     
805    }
806
807    if (iDIJETAN) {
808       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskDiJets.C");
809       AliAnalysisTaskDiJets *taskdijets = 0;
810       if(iDIJETAN&1)taskdijets = AddTaskDiJets(); 
811       if (!taskdijets) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJets cannot run for this train conditions - EXCLUDED");
812       if(iDIJETAN&2){
813         taskdijets = AddTaskDiJets("jetsAOD_CDF07"); 
814         taskdijets = AddTaskDiJets("jetsAOD_DA07"); 
815         taskdijets = AddTaskDiJets("jetsAOD_FASTJET07"); 
816         taskdijets = AddTaskDiJets("jetsAOD_FASTKT07"); 
817         taskdijets = AddTaskDiJets("jetsAOD_SISCONE07"); 
818         taskdijets = AddTaskDiJets("jetsAOD_UA107");
819       }
820    }
821
822    if(iPWG1QASym){
823      gROOT->LoadMacro("$ALICE_ROOT/PWG1/PilotTrain/AddTaskQAsym.C");
824      AliAnalysisTaskQASym *taskQASym = AddTaskQAsym(-1);
825      if (!taskQASym) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskQASym cannot run for this train conditions - EXCLUDED");
826    }
827
828
829
830    if(iPWG4TmpSourceSara){
831      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskEta.C");
832      AliAnalysisTaskEta *taskEta = AddTaskEta();
833      if (!taskEta) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskEta cannot run for this train conditions - EXCLUDED");
834    }
835
836
837    if(iPWG4JetServices){
838      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetServices.C");
839      AliAnalysisTaskJetServices *taskjetServ = 0;
840      taskjetServ = AddTaskJetServices();
841      if (!taskjetServ) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJetServices cannot run for this train conditions - EXCLUDED");
842      if(kGridRunRange[0]>0)taskjetServ->SetRunRange(kGridRunRange[0],kGridRunRange[1]);
843      else taskjetServ->SetRunRange(110000,160000);
844      taskjetServ->SetMCData(kIsMC);
845      taskjetServ->SetUsePhysicsSelection((Bool_t)iPhysicsSelection);
846      taskjetServ->SetPhysicsSelectionFlag(iPhysicsSelectionFlag); // 
847      taskjetServ->SetNonStdFile(kDeltaAODJetName.Data());
848      taskjetServ->SetTrackEtaWindow(fTrackEtaWindow);
849      taskjetServ->SetFilterMask(kHighPtFilterMask);
850      if(kIsPbPb){
851        if(kDeltaAODJetName.Length()>0&&kFilterAOD)taskjetServ->SetFilterAODCollisions(kTRUE);
852        //       else if(iAODanalysis)taskjetServ->SetFilterAODCollisions(kTRUE);
853        //       taskjetServ->SetDebugLevel(3);
854        taskjetServ->SetZVertexCut(8.);
855      }
856      if(iAODanalysis){
857        //  
858        taskjetServ->SetAODInput(kTRUE);
859      }
860    }
861
862    if(iPWG4JetSpectrum){
863      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetSpectrum2.C");
864      AliAnalysisTaskJetSpectrum2 *taskjetSpectrum = 0;
865      TString bkgClusters = kDefaultJetBackgroundBranch.Data(); 
866      bkgClusters.ReplaceAll(Form("%s_",AliAODJetEventBackground::StdBranchName()),"");
867      Printf("############# Possible jet branches ###################");
868      for(int iJF = 0;iJF < kJetListSpectrum.GetSize();iJF++){
869        TObjString *objStr = (TObjString*)kJetListSpectrum.At(iJF);
870        Printf("%3d: %s",iJF+1,objStr->GetString().Data());
871      }
872
873      if(iPWG4JetSpectrum&1){
874        if(kIsPbPb){
875          for(int iJF = 0;iJF < kJetListSpectrum.GetSize();iJF++){
876            Long64_t value = kJetMapSpectrum(iJF+1);
877            Printf("iJF: %d value: %d", iJF+1,(Int_t)value);
878            if(value==0)continue;
879            TObjString *objStr = (TObjString*)kJetListSpectrum.At(iJF);
880            TString bName1 = objStr->GetString().Data();
881            TString bName2[3];
882            
883            TObjString *objStrBkg = (TObjString*)kJetListSpectrum.At(iJF);
884            TString bBkgName1(""); 
885            TString bBkgName2[3];
886            
887            Long64_t valueBkg1 = kJetBackMapSpectrum(iJF+1);
888            if(valueBkg1>0){
889              TObjString *objStrBkg = (TObjString*)kJetListSpectrum.At(valueBkg1-1);
890              bBkgName1 = objStrBkg->GetString().Data();
891            }
892            
893            if(value>0){
894              Int_t iJF2 = -1; 
895              for(int i = 0;i<3;i++){
896                iJF2 = value/kJetMapOffset[i]-1;
897                value = value%kJetMapOffset[i];
898                Printf("%d %d", iJF2+1,(Int_t)value);
899                if(iJF2>=0&&iJF2<kJetListSpectrum.GetSize()){
900                  TObjString *objStr2 = (TObjString*)kJetListSpectrum.At(iJF2);
901                  bName2[i] = objStr2->GetString().Data();
902                  Long64_t valueBkg2 = kJetBackMapSpectrum(iJF2+1);
903                  if(valueBkg2>0){
904                    TObjString *objStrBkg2 = (TObjString*)kJetListSpectrum.At(valueBkg2-1);
905                    bBkgName2[i] = objStrBkg2->GetString().Data();
906                  }
907                }
908              }
909            }
910            
911            
912            // loop over all centralities
913            for(int ic = 0;ic<5;ic++){
914              if(ic==0)continue;
915              Bool_t bDone = kFALSE;
916              for(int i = 0;i<3;i++){
917                Printf("%s/%s %s/%s",bName1.Data(),bBkgName1.Data(),bName2[i].Data(),bBkgName2[i].Data());
918                if(bName2[i].Length()){
919                  taskjetSpectrum = AddTaskJetSpectrum2(bName1.Data(),bName2[i].Data(),kDeltaAODJetName.Data(),kHighPtFilterMask,AliVEvent::kMB,0,ic);
920                  bDone = kTRUE; 
921                }
922                else{
923                  if(!bDone){
924                    taskjetSpectrum = AddTaskJetSpectrum2(bName1.Data(),bName2[i].Data(),kDeltaAODJetName.Data(),kHighPtFilterMask,AliVEvent::kMB,0,ic);
925                    bDone = kTRUE; 
926                  }
927                  else{
928                    continue;
929                  }
930                }
931                // setting all the other things...
932                taskjetSpectrum->SetTrackEtaWindow(fTrackEtaWindow);
933                taskjetSpectrum->SetJetEtaWindow(fJetEtaWindow);
934                if(ic!=1){
935                  taskjetSpectrum->SetFlagJetType(AliAnalysisTaskJetSpectrum2::kJetRecFull,0);
936                  taskjetSpectrum->SetFlagJetType(AliAnalysisTaskJetSpectrum2::kJetGenFull,0);
937                }
938                if(bName2[i].Length()==0){
939                  taskjetSpectrum->SetFlagJetType(AliAnalysisTaskJetSpectrum2::kJetGenFull,0);
940                  taskjetSpectrum->SetFlagJetType(AliAnalysisTaskJetSpectrum2::kJetGen,0);
941                }
942                if(iAODanalysis==1){
943                  taskjetSpectrum->SetAODJetInput(kTRUE);
944                  taskjetSpectrum->SetAODTrackInput(kTRUE);
945                }
946                else if (iAODanalysis==2){
947                  taskjetSpectrum->SetAODTrackInput(kTRUE);
948                  taskjetSpectrum->SetAODJetInput(kFALSE);
949                }
950                //              taskjetSpectrum->SetDebugLevel(11);
951                taskjetSpectrum->SetBranchBkgRec(bBkgName1.Data());
952                taskjetSpectrum->SetBranchBkgGen(bBkgName2[i].Data());
953              } 
954            }
955          }
956        }
957        else{ // ! PbPb
958          Int_t i = 0;
959
960          taskjetSpectrum = AddTaskJetSpectrum2(kDefaultJetBranch.Data(),
961                                                "",kDeltaAODJetName.Data(),kHighPtFilterMask,AliVEvent::kMB,0,i);
962          
963
964          
965          if(kDefaultJetBranchMC.Length()){
966            taskjetSpectrum = AddTaskJetSpectrum2(kDefaultJetBranch.Data(),
967                                                kDefaultJetBranchMC.Data(),kDeltaAODJetName.Data(),kHighPtFilterMask,AliVEvent::kMB,0,i);
968            //      taskjetSpectrum->SetMinJetPt(10);
969            taskjetSpectrum->SetTrackEtaWindow(fTrackEtaWindow);
970            taskjetSpectrum->SetJetEtaWindow(fJetEtaWindow);
971            taskjetSpectrum->SetBranchBkgRec(bkgClusters.Data());
972            taskjetSpectrum->SetBranchBkgGen(bkgClusters.Data());
973            if(iAODanalysis)SetAODInput(taskjetSpectrum);
974          }
975          if(kDefaultJetBranchMC2.Length()){
976            taskjetSpectrum = AddTaskJetSpectrum2(kDefaultJetBranch.Data(),
977                                                  kDefaultJetBranchMC2.Data(),kDeltaAODJetName.Data(),kHighPtFilterMask,AliVEvent::kMB,0,i);
978            //      taskjetSpectrum->SetMinJetPt(10);
979            taskjetSpectrum->SetTrackEtaWindow(fTrackEtaWindow);
980            taskjetSpectrum->SetJetEtaWindow(fJetEtaWindow);
981            taskjetSpectrum->SetBranchBkgRec(bkgClusters.Data());
982            taskjetSpectrum->SetBranchBkgGen(bkgClusters.Data());
983            if(iAODanalysis)SetAODInput(taskjetSpectrum);
984          }
985
986          /*
987          TString tmp2(kDefaultJetBranch.Data());
988          tmp2.ReplaceAll(Form(kJetSubtractMask2.Data(),0),Form(kJetSubtractMask2.Data(),2));
989          taskjetSpectrum = AddTaskJetSpectrum2(tmp2.Data(),kDefaultJetBranch.Data(),kDeltaAODJetName.Data(),kHighPtFilterMask,AliVEvent::kMB,0,i);
990          //      taskjetSpectrum->SetDebugLevel(3);
991          //        taskjetSpectrum->SetMinJetPt(10);
992          taskjetSpectrum->SetBranchBkgRec(bkgClusters.Data());
993          taskjetSpectrum->SetBranchBkgGen(bkgClusters.Data());
994          taskjetSpectrum->SetTrackEtaWindow(0.8);
995          taskjetSpectrum->SetJetEtaWindow(0.4);
996
997          // check the old subtracted vs. the new subtracted
998          TString tmp3(kDefaultJetBranch.Data());
999          tmp3.ReplaceAll(Form(kJetSubtractMask2.Data(),0),Form(kJetSubtractMask2.Data(),3));
1000          taskjetSpectrum = AddTaskJetSpectrum2(tmp3.Data(),kDefaultJetBranch.Data(),kDeltaAODJetName.Data(),kHighPtFilterMask,AliVEvent::kMB,0,i);
1001          //      taskjetSpectrum->SetDebugLevel(3);
1002          //        taskjetSpectrum->SetMinJetPt(10);
1003          taskjetSpectrum->SetBranchBkgRec(bkgClusters.Data());
1004          taskjetSpectrum->SetBranchBkgGen(bkgClusters.Data());
1005          taskjetSpectrum->SetTrackEtaWindow(0.8);
1006          taskjetSpectrum->SetJetEtaWindow(0.4);
1007          if(iAODanalysis)SetAODInput(taskjetSpectrum);
1008          */
1009        }
1010        if (!taskjetSpectrum) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJetSpectrum2 cannot run for this train conditions - EXCLUDED");
1011      }
1012    }
1013    AliAnalysisManager::SetCommonFileName("PWG4_Fragmentation.root");
1014    if(iPWG4Fragmentation){
1015      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskFragmentationFunction.C");
1016        AliAnalysisTaskFragmentationFunction *taskFrag = 0;
1017        if(kUseAODMC){
1018
1019        }
1020        else{
1021
1022
1023          for(int ic = 1;ic < 5;ic++){
1024            // Anti-kT
1025            taskFrag = AddTaskFragmentationFunction(1<<23,kHighPtFilterMask, ic);
1026            if(kDeltaAODJetName.Length()>0)taskFrag->SetNonStdFile(kDeltaAODJetName.Data());
1027            if(iAODanalysis==2)taskFrag->UseAODInputJets(kFALSE);
1028
1029            // UA1
1030            taskFrag = AddTaskFragmentationFunction(1<<0,kHighPtFilterMask, ic); 
1031            if(kDeltaAODJetName.Length()>0)taskFrag->SetNonStdFile(kDeltaAODJetName.Data());
1032            if(iAODanalysis==2)taskFrag->UseAODInputJets(kFALSE);
1033
1034          // SISCONE 
1035            if(ic==1){
1036              /*
1037                taskFrag = AddTaskFragmentationFunction(1<<28,kHighPtFilterMask, ic);
1038                taskFrag = AddTaskFragmentationFunction(1<<29,kHighPtFilterMask, ic);
1039                taskFrag = AddTaskFragmentationFunction(1<<30,kHighPtFilterMask, ic);
1040              */
1041
1042
1043
1044              // Anti-kT B2 - B3
1045              if(!iAODanalysis==1){
1046                taskFrag = AddTaskFragmentationFunction(1<<26,kHighPtFilterMask, ic);
1047                if(kDeltaAODJetName.Length()>0)taskFrag->SetNonStdFile(kDeltaAODJetName.Data());
1048                if(iAODanalysis==2)taskFrag->UseAODInputJets(kFALSE);
1049                
1050                taskFrag = AddTaskFragmentationFunction(1<<27,kHighPtFilterMask, ic);
1051                if(kDeltaAODJetName.Length()>0)taskFrag->SetNonStdFile(kDeltaAODJetName.Data());
1052                if(iAODanalysis==2)taskFrag->UseAODInputJets(kFALSE);
1053              }
1054            }
1055
1056          } 
1057
1058
1059        }
1060        if (!taskFrag) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskFragmentationFunction cannot run for this train conditions - EXCLUDED");
1061    }
1062
1063    if(iPWG4JetChem){
1064      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetChem.C");
1065      AliAnalysisTask *taskChem = AddTaskJetChem(kHighPtFilterMask);
1066      if (!taskChem) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJetChem cannot run for this train conditions - EXCLUDED");
1067    }
1068
1069    if (iPWG4JetResponse) {
1070      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetResponse.C");
1071      AliAnalysisTask *taskJetResponse = 0;
1072
1073      if(iJETAN){
1074         taskJetResponse = AddTaskJetResponse("jets", "FASTJET", 0.4, kHighPtFilterMask, 0.15, 0);
1075         taskJetResponse = AddTaskJetResponse("jets", "FASTJET", 0.4, kHighPtFilterMask, 0.15, 1);
1076
1077         taskJetResponse = AddTaskJetResponse("jets", "UA1", 0.4, kHighPtFilterMask, 1., 0);
1078         taskJetResponse = AddTaskJetResponse("jets", "UA1", 0.4, kHighPtFilterMask, 1., 2);
1079      }
1080      if(iPWG4Cluster){
1081         taskJetResponse = AddTaskJetResponse("clusters", "ANTIKT", 0.4, kHighPtFilterMask, 0.15, 0);
1082         taskJetResponse = AddTaskJetResponse("clusters", "ANTIKT", 0.4, kHighPtFilterMask, 0.15, 1);
1083      }
1084      if (!taskJetResponse) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJetResponse cannot run for this train conditions - EXCLUDED");
1085
1086    }
1087
1088    if(iPWG4JCORRAN){
1089      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJCORRANTask.C");
1090      AliJCORRANTask* corran = AddTaskJCORRAN(kDeltaAODJCORRANName.Data(),0);
1091      if(!corran)::Warning("AnalysisTrainPWG4Jets", "AliJCORRANTask cannot run for this train conditions - EXCLUDED");
1092      else{
1093        if(kDeltaAODJCORRANName.Length()>0)mgr->RegisterExtraFile(kDeltaAODJCORRANName.Data()); 
1094      }
1095    }
1096
1097    if(iPWG4UE){
1098      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskUE.C");
1099      AliAnalysisTaskUE *taskUE = 0;
1100      if(iPWG4UE&1)taskUE = AddTaskUE(); 
1101      if(iPWG4UE&2){
1102        taskUE  =AddTaskUE("jetsAOD_CDF04","CDF", "LJ", "TRANSV","MSP"); //finder not yet in train
1103        //       taskUE  =AddTaskUE("jetsAOD_CDF07","CDF", "LJ", "TRANSV","MSP");
1104        taskUE  =AddTaskUE("jetsAOD_SISCONE04","CDF", "LJ", "TRANSV","MSP");
1105        //       taskUE  =AddTaskUE("jetsAOD_SISCONE07","CDF", "LJ", "TRANSV","MSP"); //finder not yet in train
1106        taskUE  =AddTaskUE("jetsAOD_ICDF","CDF","LJ","TRANSV","MSP");
1107        taskUE  =AddTaskUE("jetsAOD_FASTKT04","CDF", "LJ", "TRANSV","MSP");
1108        //       taskUE  =AddTaskUE("jetsAOD_FASTKT07","CDF", "LJ", "TRANSV","MSP"); //finder not yet in train
1109        taskUE  =AddTaskUE("jetsAOD_NONE","CDF", "MP_eta05", "TRANSV","MSP");
1110        taskUE  =AddTaskUE("jetsAOD_NONE","CDF", "MP_eta09", "TRANSV","MSP");
1111      }
1112
1113      if (!taskUE) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskUE cannot run for this train conditions - EXCLUDED");
1114    }
1115
1116    if(iPWG4LeadingUE){
1117      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskLeadingTrackUE.C");
1118      AliAnalysisTaskLeadingTrackUE *taskLeadingUE = AddTaskLeadingTrackUE(kUseMC);
1119      if (!taskLeadingUE) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTasLeadingTrackkUE cannot run for this train conditions - EXCLUDED");
1120      //     taskLeadingUE->SetFilterBit(64);
1121    }
1122
1123
1124    if(iPWG4CorrectionsUE){
1125      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskCorrectionsUE.C");
1126      AliAnalysisTaskCorrectionsUE *taskCorrectionsUE = 0;
1127      if(iPWG4CorrectionsUE&1)taskCorrectionsUE = AddTaskCorrectionsUE("jetsAOD_NONE","CDF","MP_eta05","TRANSV","MSP",kFALSE);
1128      if (!taskCorrectionsUE) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskCorrectionsUE cannot run for this train conditions - EXCLUDED");
1129    }
1130
1131    if(iPWG4ThreeJets){
1132      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskThreeJets.C");
1133      AliAnalysisTaskThreeJets *taskThree = AddTaskThreeJets();
1134      if(!taskThree)::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskThreets cannot run for this train conditions - EXCLUDED");
1135    }
1136    if(iPWG4QGSep){
1137      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskQGSep.C");
1138      AliAnalysisTaskQGSep *taskQGSep = AddTaskQGSep(kUseMC,iAODanalysis);
1139      if(!taskQGSep)::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskQGSep cannot run for this train conditions - EXCLUDED");
1140    }
1141   
1142
1143    if(iPWG4Minijet){
1144      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskMinijet.C");
1145      AliAnalysisTaskMinijet *taskMini = AddTaskMinijet(-1,"esd",kUseMC,kGridDataSet);
1146      // if we ha highmult trigger add another task
1147      if(!taskMini)::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskMinjet cannot run for this train conditions - EXCLUDED");
1148    }
1149
1150    AliAnalysisManager::SetCommonFileName("PWG4_HighPtQA.root");
1151    if(iPWG4PtQAMC){
1152      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPWG4HighPtQAMC.C");
1153      AliPWG4HighPtQAMC *taskQAMC = 0;
1154      if(kUseMC){
1155        if(iPWG4PtQAMC&1){
1156          taskQAMC = AddTaskPWG4HighPtQAMC(kGridDataSet.Data(),0);
1157          taskQAMC = AddTaskPWG4HighPtQAMC(kGridDataSet.Data(),1);
1158          taskQAMC = AddTaskPWG4HighPtQAMC(kGridDataSet.Data(),2);
1159          taskQAMC = AddTaskPWG4HighPtQAMC(kGridDataSet.Data(),3);
1160        }
1161      }
1162      if (!taskQAMC) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskQAMC cannot run for this train conditions - EXCLUDED");
1163    }
1164
1165    if(iPWG4PtTrackQA){
1166      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPWG4HighPtTrackQA.C");
1167
1168      AddTaskPWG4HighPtTrackQAAll(kGridDataSet.Data(),kIsPbPb,iAODanalysis);
1169
1170    }
1171
1172    if(iPWG4PtQATPC){
1173      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPWG4HighPtQATPConly.C");
1174      AliPWG4HighPtQATPConly *taskQATPC = 0;
1175      if(iPWG4PtQATPC&1)taskQATPC = AddTaskPWG4HighPtQATPConly(kGridDataSet.Data(),1);
1176      if(iPWG4PtQATPC&2)taskQATPC = AddTaskPWG4HighPtQATPConly(kGridDataSet.Data(),2);
1177
1178  if (!taskQATPC) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskQATPC cannot run for this train conditions - EXCLUDED");
1179    }
1180
1181    if(iPWG4Cosmics){
1182      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPWG4CosmicCandidates.C");
1183
1184      AliPWG4CosmicCandidates *taskPWG4CosmicCandidates = AddTaskPWG4CosmicCandidates(0);
1185      taskPWG4CosmicCandidates = AddTaskPWG4CosmicCandidates(1);
1186
1187      if (!taskPWG4CosmicCandidates) ::Warning("AnalysisTrainPWG4Jets", "AddTaskPWG4CosmicCandidates cannot run for this train conditions - EXCLUDED");
1188    }
1189
1190
1191    if(iPWG4PtSpectra){
1192      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPWG4HighPtSpectra.C");
1193      AddTaskPWG4HighPtSpectraAll(kGridDataSet.Data(),kIsPbPb);
1194    }
1195
1196    if(iPWG4KMeans){
1197      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskKMeans.C");
1198      AliAnalysisTaskKMeans *taskKMeans = AddTaskKMeans();
1199      if (!taskKMeans) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskKMenans cannot run for this train conditions - EXCLUDED");
1200    }
1201
1202    if(iPWG4PartCorr){
1203      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPartCorr.C");
1204      AliAnalysisTaskParticleCorrelation *taskpartcorrPHOS = AddTaskPartCorr("AOD", "PHOS",kFALSE,kIsMC);
1205      if (!taskpartcorrPHOS) ::Warning("AnalysisTrainNew", "AliAnalysisTaskParticleCorrelation PHOS cannot run for this train conditions - EXCLUDED");
1206      AliAnalysisTaskParticleCorrelation *taskpartcorrEMCAL = AddTaskPartCorr("AOD", "EMCAL",kFALSE,kIsMC);
1207      if (!taskpartcorrEMCAL) ::Warning("AnalysisTrainNew", "AliAnalysisTaskParticleCorrelation EMCAL cannot run for this train conditions - EXCLUDED");
1208      if(kDeltaAODPartCorrName.Length()>0)mgr->RegisterExtraFile(kDeltaAODPartCorrName.Data());
1209    } 
1210
1211    if(iPWG4CaloQA){
1212      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/QA/AddTaskCalorimeterQA.C");
1213      AliAnalysisTaskParticleCorrelation *taskcaloQA =  AddTaskCalorimeterQA("ESD",kFALSE,kIsMC,kCaloQAOutputFileName.Data());
1214      if(!taskcaloQA)::Warning("AnalysisTrainNew", "AliAnalysisTaskParticleCorrelation QA cannot run - EXCLUDED");
1215      //  if(kCaloQAOutputFileName.Length()>0)mgr->RegisterExtraFile(kCaloQAOutputFileName.Data());
1216    } 
1217
1218    if(iPWG4JetCorr){
1219      //     using namespace JetCorrelHD;
1220      TString cdir = gSystem->WorkingDirectory();
1221      gSystem->ChangeDirectory(gSystem->ExpandPathName("$ALICE_ROOT/PWG4/macros/"));
1222      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetCorrel.C");
1223      AliAnalysisTaskJetCorrel *taskjetcorr = AddTaskJetCorrel();
1224      gSystem->ChangeDirectory(cdir);
1225      if (!taskjetcorr) ::Warning("AnalysisTrainNew", "AliAnalysisTaskJetCorrel  cannot run for this train conditions - EXCLUDED");
1226    } 
1227
1228    if(iPWG4Tagged){
1229      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskTaggedPhotons.C");
1230      AliAnalysisTaskTaggedPhotons * taskTagged = AddTaskTaggedPhotons(kFALSE); // EMCAL
1231      taskTagged = AddTaskTaggedPhotons(kTRUE); // PHOS 
1232      if (!taskTagged) ::Warning("AnalysisTrainNew", "AliAnalysisTaskTaggedPhotons  cannot run for this train conditions - EXCLUDED");     
1233    }
1234    if (iPWG4omega3pi) {
1235      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskomega3pi.C");
1236      AliAnalysisTaskOmegaPi0PiPi *taskomega3pi = AddTaskomega3pi();
1237      if (!taskomega3pi) ::Warning("AnalysisTrainNew", "AliAnalysisTaskomega3pi cannot run\
1238  for these train conditions - EXCLUDED");
1239    }
1240
1241    // PWG4 gamma conversion analysis
1242    if (iPWG4GammaConv) {
1243       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskGammaConversion.C");
1244       TString cdir = gSystem->WorkingDirectory();
1245       gSystem->ChangeDirectory(gSystem->ExpandPathName("$ALICE_ROOT/PWG4/macros/"));
1246       //      TString gcArguments = "-run-on-train -run-jet -run-chic -run-neutralmeson -run-cf";
1247       //      TString gcArguments = "-run-on-train -run-jet -run-neutralmeson -run-cf -use-own-xyz";
1248       //      TString gcArguments = "-run-on-train -run-jet -run-neutralmeson -run-cf -use-own-xyz";
1249       TString gcArguments = "-run-on-train -run-jet -run-omega-meson -use-own-xyz -run-neutralmeson -no-aod";
1250       //      TString kGCAnalysisCutSelectionId="9003562000100310";
1251       //      TString kGCAnalysisCutSelectionId="9003562000100312";
1252       //      gcArguments.Append(Form(" -set-cut-selection %s ",kGCAnalysisCutSelectionId.Data()));
1253       if(!kIsMC)gcArguments += " -mc-off";
1254       AliAnalysisTaskGammaConversion * taskGammaConversion = AddTaskGammaConversion(gcArguments,mgr->GetCommonInputContainer());
1255       gSystem->ChangeDirectory(cdir);
1256       taskGammaConversion->SelectCollisionCandidates();
1257       if (!taskGammaConversion) ::Warning("AnalysisTrainNew", "AliAnalysisTaskGammaConversion cannot run for these train conditions - EXCLUDED");
1258    }   
1259
1260    if (iPWG4CaloConv) {
1261       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskCaloConv.C");
1262       AliAnalysisTaskCaloConv * taskCaloConv = AddTaskCaloConv();
1263       if (!taskCaloConv) ::Warning("AnalysisTrainNew", "AliAnalysisTaskCaloConv cannot run for these train conditions - EXCLUDED");
1264    }   
1265
1266
1267
1268    //==========================================================================
1269    // FOR THE REST OF THE TASKS THE MACRO AddTaskXXX() is not yet implemented/
1270    // Run the analysis
1271    //    
1272    if (kPluginUse) {
1273       AliAnalysisGrid *alienHandler = CreateAlienHandler(plugin_mode);
1274       AliAnalysisManager::GetAnalysisManager()->SetGridHandler(alienHandler);
1275    }
1276    
1277    if (mgr->InitAnalysis()) {
1278      mgr->PrintStatus();
1279      // if (kSaveTrain || strlen(config_file)) gSystem->ChangeDirectory(kTrainName);
1280      if (!strcmp(plugin_mode,"submit")&&smode=="GRID"){
1281        TString alien_workdir = gGrid->GetHomeDirectory();
1282        if (iAODanalysis) alien_workdir += "analysisAOD";
1283        else              alien_workdir += "analysisESD";
1284        if(kGridDataSet.Length()>0)alien_workdir += Form("/%s%s",kGridDataSet.Data(),kGridExtraAliendirLevel.Data());
1285        AliAnalysisAlien *gridhandler = (AliAnalysisAlien*)mgr->GetGridHandler();
1286        printf("=== AnalysisTrainPWG4Jets:: Registering jdl in the work directory alien://%s/%s, should be done by the manager! ===\n",
1287               alien_workdir.Data(),gridhandler->GetGridOutputDir());
1288
1289        TString dest;
1290        dest = Form("%s/%s/%s.jdl",alien_workdir.Data(),gridhandler->GetGridOutputDir(),kTrainName.Data());
1291        if(AliAnalysisAlien::FileExists(dest.Data())){
1292          Printf("%s exist on grid removing...",dest.Data());
1293          gGrid->Rm(dest.Data());
1294        }
1295        Printf("%s copy ...",dest.Data());
1296        TFile::Cp(Form("file:%s.jdl",kTrainName.Data()),Form("alien://%s",dest.Data()));
1297
1298
1299        TString dest;
1300        dest = Form("%s/%s/%s_merge.jdl",alien_workdir.Data(),gridhandler->GetGridOutputDir(),kTrainName.Data());
1301        if(AliAnalysisAlien::FileExists(dest.Data())){
1302          Printf("%s exist on grid removing...",dest.Data());
1303          gGrid->Rm(dest.Data());
1304        }
1305        Printf("%s copy ...",dest.Data());
1306        TFile::Cp(Form("file:%s_merge.jdl",kTrainName.Data()),Form("alien://%s",dest.Data()));
1307        
1308        dest = Form("%s/%s/%s_merge_final.jdl",alien_workdir.Data(),gridhandler->GetGridOutputDir(),kTrainName.Data());
1309        if(AliAnalysisAlien::FileExists(dest.Data())){
1310          Printf("%s exist on grid removing...",dest.Data());
1311          gGrid->Rm(dest.Data());
1312        }
1313        Printf("%s copy ...",dest.Data());
1314        TFile::Cp(Form("file:%s_merge.jdl",kTrainName.Data()),Form("alien://%s",dest.Data()));
1315      }
1316      AliLog::SetGlobalLogLevel(AliLog::kError);
1317      if((kUseSysInfo>0&&smode=="LOCAL")||!strcmp(plugin_mode, "test")){
1318        TFile * fM = TFile::Open("manager_local.root","RECREATE");
1319        mgr->Write();
1320        fM->Close();
1321      }
1322      
1323      // grmpf, aliroot error handler overwrites root
1324      gErrorIgnoreLevel = kErrorIgnoreLevel;
1325      if(gErrorIgnoreLevel>3000) AliLog::SetGlobalLogLevel(AliLog::kFatal);
1326      StartAnalysis(smode, chain);
1327      if((kUseSysInfo>0&&smode=="LOCAL")||!strcmp(plugin_mode, "test")){
1328        for(int i = 0;i < mgr->GetTopTasks()->GetEntries();i++){
1329          mgr->ProfileTask(i);
1330        }
1331      }
1332      if (!strcmp(plugin_mode, "offline")&&smode=="GRID"){
1333        // Offline mode path files
1334        //       PatchJDL();
1335        //       PatchAnalysisMacro();
1336      }
1337
1338      if (kSaveTrain && smode=="GRID") {
1339        AliAnalysisAlien *gridhandler = (AliAnalysisAlien*)mgr->GetGridHandler();
1340        TString alien_workdir = gGrid->GetHomeDirectory();
1341        if (iAODanalysis) alien_workdir += "analysisAOD";
1342        else              alien_workdir += "analysisESD";
1343        if(kGridDataSet.Length()>0)alien_workdir += Form("/%s%s",kGridDataSet.Data(),kGridExtraAliendirLevel.Data());
1344        //     kGridOutdir = gridhandler->GetGridOutputDir();
1345        printf("=== Registering ConfigTrain.C in the work directory <%s> ===\n",
1346                 alien_workdir.Data());
1347        if (AliAnalysisAlien::FileExists(Form("%s/%sConfig.C", alien_workdir.Data(), kTrainName.Data())))
1348          gGrid->Rm(Form("%s/%sConfig.C", alien_workdir.Data(), kTrainName.Data()));
1349        if (strcmp(plugin_mode, "test"))
1350          TFile::Cp(Form("file:%sConfig.C",kTrainName.Data()), Form("alien://%s/%sConfig.C", alien_workdir.Data(), kTrainName.Data()));
1351      }
1352    }
1353 }
1354
1355 //______________________________________________________________________________
1356 void StartAnalysis(const char *mode, TChain *chain) {
1357 // Start analysis.
1358    Int_t imode = -1;
1359    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
1360    if (!strcmp(mode, "LOCAL")) imode = 0;
1361    if (!strcmp(mode, "PROOF")) imode = 1;
1362    if (!strcmp(mode, "GRID"))  imode = 2;
1363    switch (imode) {
1364       case 0:
1365          if (!chain) {
1366             ::Error("AnalysisTrainPWG4Jets.C::StartAnalysis", "Cannot create the chain");
1367             return;
1368          }   
1369          mgr->StartAnalysis(mode, chain,kNumberOfEvents);
1370          return;
1371       case 1:
1372          if (!kProofDataSet.Length()) {
1373             ::Error("AnalysisTrainPWG4Jets.C::StartAnalysis", "kProofDataSet is empty");
1374             return;
1375          }   
1376          mgr->StartAnalysis(mode, kProofDataSet, kProofEvents,kProofOffset);
1377          return;
1378       case 2:
1379          if (kPluginUse) {
1380             if (!mgr->GetGridHandler()) {
1381                ::Error("AnalysisTrainPWG4Jets.C::StartAnalysis", "Grid plugin not initialized");
1382                return;
1383             }   
1384             mgr->StartAnalysis("grid",chain,kNumberOfEvents);
1385          } else {
1386             if (!chain) {
1387                ::Error("AnalysisTrainPWG4Jets.C::StartAnalysis", "Cannot create the chain");
1388                return;
1389             }   
1390             //            mgr->StartAnalysis(mode, chain);
1391             mgr->StartAnalysis(mode, chain,kNumberOfEvents);
1392          }   
1393          return;
1394    }      
1395 }          
1396     
1397 //______________________________________________________________________________
1398 void CheckModuleFlags(const char *mode) {
1399 // Checks selected modules and insure compatibility
1400    Int_t imode = -1;
1401    if (!strcmp(mode, "LOCAL")) imode = 0;
1402    if (!strcmp(mode, "PROOF")) imode = 1;
1403    if (!strcmp(mode, "GRID"))  imode = 2;
1404
1405
1406    if (kUseCPAR) {
1407      kPluginAliRootVersion    = ""; // NO aliroot if we use CPAR
1408    }
1409
1410    if (imode==1) {
1411       if (!kUsePAR) {
1412          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PAR files enabled due to PROOF analysis");
1413          kUsePAR = kTRUE;
1414       }   
1415    }  
1416    if (imode != 2) {
1417       ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "AliEn plugin disabled since not in GRID mode");
1418       kPluginUse = kFALSE; 
1419    }   
1420
1421
1422    if(!kIsMC){
1423      // switch off anthin related to MC
1424      kUseMC = 0;
1425      kUseAODMC = 0;
1426      kUseTR = kFALSE;
1427    }
1428
1429    // Decide if we have PbPb
1430    if(kGridDataSet.CompareTo("LHC10h")==0||kGridDataSet.Contains("LHC10h")) {
1431      Printf("Using settings for Pb+Pb");
1432      kIsPbPb = true;
1433    }
1434
1435    
1436
1437    if (iAODanalysis) {
1438    // AOD analysis
1439       if (kUseMC)
1440          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "MC usage disabled in analysis on AOD's");
1441       if (kUseAODTags)
1442          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "AOD tags usage disabled in analysis on AOD's");
1443       kUseMC = kFALSE;
1444       kUseTR = kFALSE;
1445       kUseAODTags = kFALSE;
1446       if (iESDfilter)
1447          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "ESD filter disabled in analysis on AOD's");
1448       iESDfilter   = 0;
1449       if (iPhysicsSelection)
1450          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "Physics Selection disabled in analysis on AOD's");
1451       iPhysicsSelection   = 0;
1452       if (!iAODhandler) {
1453          if (iJETAN) 
1454             ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "JETAN disabled in analysis on AOD's without AOD handler");
1455          iJETAN = 0;
1456          iDIJETAN = 0;
1457       }
1458       // Disable tasks that do not work yet on AOD data
1459       if(iPWG4JCORRAN)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 JCORRAN disabled in analysis on AOD's");
1460       iPWG4JCORRAN = 0;
1461       if( iPWG4PtQAMC)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 PtQAMC disabled in analysis on AOD's");
1462       iPWG4PtQAMC        = 0;
1463       if( iPWG4PtQATPC)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 PtTPC disabled in analysis on AOD's");
1464       iPWG4PtQATPC        = 0;
1465       if( iPWG4Cosmics)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 Comics disabled in analysis on AOD's");
1466       iPWG4Cosmics        = 0;
1467
1468       if( iPWG4PtSpectra)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 PtQAMC disabled in analysis on AOD's");
1469       iPWG4PtSpectra     = 0;
1470       if(iPWG4KMeans)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4KMeans disabled on AOD's");
1471       iPWG4KMeans       = 0;
1472       if (iPWG4JetCorr)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4Jetcorr disabled on AOD's");
1473       iPWG4JetCorr = 0;
1474       if (iPWG4PartCorr)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4partcorr disabled on AOD's");
1475       iPWG4PartCorr = 0;
1476       if (iPWG4CaloQA)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4CaloQA disabled on AOD's");
1477       iPWG4CaloQA = 0;
1478       if (iPWG4Tagged)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4tagged disabled on AOD's");
1479       iPWG4Tagged = 0;
1480       if (iPWG4omega3pi)
1481         ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG4omega3pi disabled on AOD's");
1482       iPWG4omega3pi = 0;
1483       if(iPWG1QASym)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG1 QA Sym disabled in analysis on AOD's");
1484       if (iPWG4GammaConv)::Info("AnalysisPWG4Jets.C::CheckModuleFlags", "PWG4gammaconv disabled on AOD's");
1485       iPWG4GammaConv = 0;   
1486       iPWG1QASym     = 0;
1487       iCentralitySelection = 0;
1488    } else {   
1489    // ESD analysis
1490
1491      if(kIsPbPb){
1492        iCentralitySelection = 1;
1493      }
1494
1495      if (!kUseMC){
1496        kUseTR = kFALSE;
1497        
1498        if(kUseKinefilter)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 Kine Filter disabled in analysis without MC");
1499        kUseKinefilter = kFALSE;
1500        if( iPWG4PtQAMC)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 PtQAMC disabled in analysis without MC");
1501        iPWG4PtQAMC        = 0;
1502        if( iPWG4CorrectionsUE)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 CorrectionsUE disabled in analysis without MC");
1503        iPWG4CorrectionsUE = 0;
1504      }
1505      if (iJETAN){
1506        iESDfilter=1;
1507      }
1508       if (!iESDfilter){
1509         kUseKinefilter = kFALSE;
1510         kUseMuonfilter = kFALSE;
1511       }
1512       if(!iJETAN){
1513         iPWG4JetSpectrum = iPWG4UE =  iPWG4CorrectionsUE = iPWG4ThreeJets = iPWG4QGSep = iDIJETAN = 0;
1514       }
1515    }
1516    iPWG4JetTasks = iPWG4JetServices||iPWG4JetSpectrum||iPWG4UE||iPWG4LeadingUE||iPWG4PtQAMC||iPWG4PtTrackQA||iPWG4PtSpectra||iPWG4PtQATPC||iPWG4Cosmics||iPWG4ThreeJets||iPWG4QGSep||iPWG4JetChem||iPWG4Minijet||iPWG4Fragmentation;
1517    iPWG4PartCorrLibs = iPWG4PartCorr||iPWG4Tagged||iPWG4CaloQA;
1518    iPWG4GammaConvLib = iPWG4GammaConv||iPWG4CaloConv;
1519
1520
1521    iEMCUtilLibs = iPWG4JetTasks||iPWG4PartCorrLibs||iPWG4JCORRAN||iPWG4GammaConvLib||iJETAN;
1522    iJETANLib = iPWG4JetTasks||iJETAN||iDIJETAN;
1523
1524    if (iESDfilter) {iAODhandler=1;}
1525    if (kUseKinefilter && !kUseMC) kUseKinefilter = kFALSE;
1526    if (kUseAODTags && !iAODhandler) kUseAODTags = kFALSE;
1527
1528
1529    
1530 }
1531
1532 //______________________________________________________________________________
1533 Bool_t Connect(const char *mode) {
1534 // Connect <username> to the back-end system.
1535    Int_t imode = -1;
1536    if (!strcmp(mode, "LOCAL")) imode = 0;
1537    if (!strcmp(mode, "PROOF")) imode = 1;
1538    if (!strcmp(mode, "GRID"))  imode = 2;
1539    TString username = gSystem->Getenv("alien_API_USER");
1540    switch (imode) {
1541       case 0:
1542          break;
1543       case 1:
1544          if  (!username.Length()) {
1545             ::Error(Form("AnalysisTrainPWG4Jets.C::Connect <%s>", mode), "Make sure you:\n \
1546                            1. Have called: alien-token-init <username>\n \
1547                            2. Have called: >source /tmp/gclient_env_$UID");
1548             return kFALSE;
1549          }
1550          ::Info("AnalysisTrainPWG4Jets.C::Connect", "Connecting user <%s> to PROOF cluster <%s>", 
1551                 username.Data(), kProofCluster.Data());
1552          gEnv->SetValue("XSec.GSI.DelegProxy", "2");
1553 //         TProof::Open(Form("%s@%s:31093", username.Data(), kProofCluster.Data()));       
1554          TProof::Open(Form("%s@%s", username.Data(), kProofCluster.Data()));       
1555          if (!gProof) {
1556             if (strcmp(gSystem->Getenv("XrdSecGSISRVNAMES"), "lxfsrd0506.cern.ch"))
1557                ::Error(Form("AnalysisTrainPWG4Jets.C::Connect <%s>", mode), "Environment XrdSecGSISRVNAMES different from lxfsrd0506.cern.ch");
1558             return kFALSE;
1559          }
1560          if(kProofClearPackages)gProof->ClearPackages();
1561
1562          if(kProofSaveToAlien){
1563            TGrid::Connect("alien://");
1564            if (gGrid) {
1565              TString homedir = gGrid->GetHomeDirectory();
1566              TString workdir = homedir + kTrainName;
1567              if (!gGrid->Cd(workdir)) {
1568                gGrid->Cd(homedir);
1569                if (gGrid->Mkdir(workdir)) {
1570                  gGrid->Cd(kTrainName);
1571                  ::Info("AnalysisTrainPWG4Jets::Connect()", "Directory %s created", gGrid->Pwd());
1572                }
1573              }
1574              gGrid->Mkdir("proof_output");
1575              gGrid->Cd("proof_output");
1576              kProofOutdir = Form("alien://%s", gGrid->Pwd());
1577            }   
1578          }
1579          break;
1580       case 2:      
1581          if  (!username.Length()) {
1582             ::Error(Form("AnalysisTrainPWG4Jets.C::Connect <%s>", mode), "Make sure you:\n \
1583                            1. Have called: alien-token-init <username>\n \
1584                            2. Have called: >source /tmp/gclient_env_$UID");
1585             return kFALSE;
1586          }
1587          if (kPluginUse && !gSystem->Getenv("alien_CLOSE_SE")) {
1588             ::Error(Form("AnalysisTrainPWG4Jets.C::Connect <%s>", mode), 
1589                            "When using the AliEn plugin it is preferable to define the \
1590                            variable alien_CLOSE_SE in your environment.");
1591             return kFALSE;
1592          }
1593          ::Info("AnalysisTrainPWG4Jets.C::Connect", "Connecting user <%s> to AliEn ...", 
1594                 username.Data());
1595          TGrid::Connect("alien://");
1596          if (!gGrid || !gGrid->IsConnected()) return kFALSE;
1597          break;
1598       default:
1599          ::Error("AnalysisTrainPWG4Jets.C::Connect", "Unknown run mode: %s", mode);
1600          return kFALSE;
1601    }
1602    ::Info("AnalysisTrainPWG4Jets.C::Connect","Connected in %s mode", mode);
1603    return kTRUE;
1604 }
1605
1606 //______________________________________________________________________________
1607 Bool_t LoadCommonLibraries(const char *mode)
1608 {
1609    if (!gSystem->Getenv("ALICE_ROOT")) {
1610       ::Error("AnalysisTrainPWG4Jets.C", "Analysis train requires that ALICE_ROOT is set to pick up Configurations"); 
1611       return kFALSE;
1612    }   
1613    
1614    // Load common analysis libraries.
1615    Int_t imode = -1;
1616    if (!strcmp(mode, "LOCAL")) imode = 0;
1617    if (!strcmp(mode, "PROOF")) imode = 1;
1618    if (!strcmp(mode, "GRID"))  imode = 2;
1619    Bool_t success = kTRUE;
1620    // ROOT libraries
1621    gSystem->Load("libTree.so");
1622    gSystem->Load("libGeom.so");
1623    gSystem->Load("libVMC.so");
1624    gSystem->Load("libPhysics.so");
1625    
1626    // Load framework classes. Par option ignored here.
1627    switch (imode) {
1628       case 0:
1629       case 2:
1630          if (kUseCPAR) {
1631             success &= LoadLibrary("STEERBase", mode, kTRUE);
1632             success &= LoadLibrary("ESD", mode, kTRUE);
1633             success &= LoadLibrary("AOD", mode, kTRUE);
1634             success &= LoadLibrary("ANALYSIS", mode, kTRUE);
1635             success &= LoadLibrary("OADB", mode, kTRUE);
1636             success &= LoadLibrary("ANALYSISalice", mode, kTRUE);
1637             success &= LoadLibrary("ROOTFILES", mode, kTRUE);
1638             //            success &= LoadLibrary("EventMixing", mode,kTRUE);
1639             success &= LoadLibrary("CORRFW", mode, kTRUE);
1640          } else {   
1641             success &= LoadLibrary("libSTEERBase.so", mode);
1642             success &= LoadLibrary("libESD.so", mode);
1643             success &= LoadLibrary("libAOD.so", mode);
1644             success &= LoadLibrary("libANALYSIS.so", mode);
1645             success &= LoadLibrary("libOADB.so", mode, kTRUE);
1646             success &= LoadLibrary("libANALYSISalice.so", mode);
1647             //            success &= LoadLibrary("libEventMixing.so", mode);
1648             success &= LoadLibrary("libCORRFW.so", mode);
1649             gROOT->ProcessLine(".include $ALICE_ROOT/include");
1650          }   
1651          break;
1652       case 1:
1653          Int_t ires = -1;
1654          if (kProofUseAFPAR && !gSystem->AccessPathName(kProofAFversion)) ires = gProof->UploadPackage(kProofAFversion);
1655          if (ires < 0) {
1656             success &= LoadLibrary("STEERBase", mode);
1657             success &= LoadLibrary("ESD", mode);
1658             success &= LoadLibrary("AOD", mode);
1659             success &= LoadLibrary("ANALYSIS", mode);
1660             success &= LoadLibrary("ANALYSISalice", mode);
1661             success &= LoadLibrary("EventMixing", mode);
1662             success &= LoadLibrary("CORRFW", mode);
1663          } else { 
1664             ires = gProof->EnablePackage(kProofAFversion);
1665             if (ires<0) success = kFALSE;
1666             success &= LoadLibrary("CORRFW", mode);
1667          }
1668          break;         
1669       default:
1670          ::Error("AnalysisTrainPWG4Jets.C::LoadCommonLibraries", "Unknown run mode: %s", mode);
1671          return kFALSE;
1672    }
1673    if (success) {
1674       ::Info("AnalysisTrainPWG4Jets.C::LoadCommodLibraries", "Load common libraries:    SUCCESS");
1675       ::Info("AnalysisTrainPWG4Jets.C::LoadCommodLibraries", "Include path for Aclic compilation:\n%s",
1676               gSystem->GetIncludePath());
1677    } else {           
1678       ::Info("AnalysisTrainPWG4Jets.C::LoadCommodLibraries", "Load common libraries:    FAILED");
1679    }   
1680       
1681    return success;
1682 }
1683
1684 //______________________________________________________________________________
1685 Bool_t LoadAnalysisLibraries(const char *mode)
1686 {
1687 // Load common analysis libraries.
1688   Bool_t success = kTRUE;
1689   if (useTender) {
1690       if (!LoadLibrary("TENDER", mode, kTRUE) ||
1691           !LoadLibrary("TENDERSupplies", mode, kTRUE)) return kFALSE;
1692    }
1693    if (iESDfilter) {
1694      /*
1695       if (!LoadLibrary("PWG3base", mode, kTRUE) ||
1696           !LoadLibrary("PWG3muon", mode, kTRUE)) return kFALSE;
1697      */
1698    }   
1699    // JETAN
1700    if (iJETANLib) {
1701      // this part needs some rework in case we do not need the fastjed finders for processing
1702      if(iEMCUtilLibs){
1703        if (!LoadLibrary("EMCALUtils", mode, kTRUE) ||
1704            !LoadLibrary("PHOSUtils", mode, kTRUE)) return kFALSE;
1705      }
1706      if (!LoadLibrary("JETAN", mode, kTRUE)) return kFALSE;
1707      if (!strcmp(mode, "PROOF")){
1708        gProof->Exec("gSystem->Load\(\"/afs/cern.ch/user/d/dperrino/public/libCGAL.so\"\)", kTRUE); 
1709        gProof->Exec("gSystem->Load\(\"/afs/cern.ch/user/d/dperrino/public/libfastjet.so\"\)", kTRUE); 
1710        // problem when loading siscone copiled with different gcc version??
1711        // gProof->Exec("gSystem->Load\(\"/afs/cern.ch/user/d/dperrino/public/libsiscone.so\"\)", kTRUE); 
1712        gProof->Exec("gSystem->Load\(\"/afs/cern.ch/user/d/dperrino/public/libSISConePlugin.so\"\)", kTRUE);      
1713      }
1714      if(!kUsePAR){ 
1715        if (!LoadLibrary("CGAL", mode, kTRUE)) return kFALSE;
1716        if (!LoadLibrary("fastjet", mode, kTRUE)) return kFALSE;
1717        if (!LoadLibrary("siscone", mode, kTRUE)) return kFALSE;
1718        if (!LoadLibrary("SISConePlugin", mode, kTRUE)) return kFALSE;
1719      }
1720      else{
1721        // par files plus FASTJET needs some extra work... need to change
1722        // the loading sequence in the auto generated .C file
1723        if (!LoadLibrary("libCGAL.so", mode, kTRUE)) return kFALSE;
1724        if (!LoadLibrary("libfastjet.so", mode, kTRUE)) return kFALSE;
1725        if (!LoadLibrary("libsiscone.so", mode, kTRUE)) return kFALSE;
1726        if (!LoadLibrary("libSISConePlugin.so", mode, kTRUE)) return kFALSE;
1727      }
1728      if (!LoadLibrary("FASTJETAN", mode, kTRUE)) return kFALSE;
1729    }
1730    if(iPWG4JetTasks){
1731      if (!LoadLibrary("PWG4JetTasks", mode, kTRUE)) return kFALSE;
1732    }
1733
1734    if(iPWG1QASym){
1735      if (!LoadSource(Form("%s/PWG1/AliAnalysisTaskQASym.cxx",gSystem->ExpandPathName("$ALICE_ROOT")), mode, kTRUE))return kFALSE;
1736    }
1737    if(iPWG4TmpSourceSara){
1738      if(!kUsePAR)gSystem->AddIncludePath("-I$ALICE_ROOT/include/JetTasks"); // ugly hack!!
1739      if(!LoadSource(Form("%s/PWG4/JetTasks/AliAnalysisTaskEta.cxx",gSystem->ExpandPathName("$ALICE_ROOT")), mode, kTRUE))return kFALSE;
1740    }
1741
1742    if (iPWG4PartCorrLibs) {   
1743       if (!LoadLibrary("PWG4PartCorrBase", mode, kTRUE) ||
1744           !LoadLibrary("PWG4PartCorrDep", mode, kTRUE)) return kFALSE;
1745    }
1746    if(iPWG4JCORRAN){
1747      // PWG4 particle correlations
1748      if(!LoadLibrary("PWG4JCORRAN",mode,kTRUE))return kFALSE;
1749    }
1750    if (iPWG4JetCorr) { 
1751      if (!LoadLibrary("PWG4JetCorrel", mode, kTRUE)) return kFALSE;
1752    }  
1753    if (iPWG4omega3pi) {
1754      if (!LoadLibrary("PWG4omega3pi", mode, kTRUE)) return kFALSE;
1755    }
1756    if (iPWG4GammaConvLib) {
1757       if (!LoadLibrary("PWG4GammaConv", mode, kTRUE)) return kFALSE;
1758    }      
1759
1760    ::Info("AnalysisTrainPWG4Jets.C::LoadAnalysisLibraries", "Load other libraries:   SUCCESS");
1761    return kTRUE;
1762 }
1763
1764 //______________________________________________________________________________
1765 Bool_t LoadLibrary(const char *module, const char *mode, Bool_t rec=kFALSE)
1766 {
1767 // Load a module library in a given mode. Reports success.
1768    Int_t imode = -1;
1769    Int_t result;
1770    TString smodule(module);
1771    if (!strcmp(mode, "LOCAL")) imode = 0;
1772    if (!strcmp(mode, "PROOF")) imode = 1;
1773    if (!strcmp(mode, "GRID"))  imode = 2;
1774    TString mod(module);
1775    if (!mod.Length()) {
1776       ::Error("AnalysisTrainPWG4Jets.C::LoadLibrary", "Empty module name");
1777       return kFALSE;
1778    }   
1779    // If a library is specified, just load it
1780    if (smodule.EndsWith(".so")) {
1781       mod.Remove(mod.Index(".so"));
1782       result = gSystem->Load(mod);
1783       if (result < 0) {
1784          ::Error("AnalysisTrainPWG4Jets.C::LoadLibrary", "Could not load library %s", module);
1785          return kFALSE;
1786       }
1787       if (rec) anaLibs += Form("%s.so ",mod.Data()); 
1788       if (rec) anaLibsExtra += Form("%s.so ",mod.Data()); 
1789       return kTRUE;
1790    } 
1791    // Check if the library is already loaded
1792    if (strlen(gSystem->GetLibraries(Form("%s.so", module), "", kFALSE)) > 0)
1793       return kTRUE;    
1794    switch (imode) {
1795       case 0:
1796       case 2:
1797          if (kUsePAR) {
1798             result = SetupPar(module);
1799             if (rec) anaPars += Form("%s.par ", module);
1800          } else {
1801             result = gSystem->Load(Form("lib%s.so", module));
1802             if (rec) anaLibs += Form("lib%s.so ", module);
1803          }   
1804          break;
1805       case 1:
1806         if(!gSystem->AccessPathName(module)){
1807           ::Info("AnalysisTrainPWG4Jets.C::LoadLibrary", "Removing directory %s",module);
1808           gSystem->Exec(Form("rm -rf %s",module));
1809         }
1810          result = gProof->UploadPackage(module);
1811          if (result<0) {
1812             result = gProof->UploadPackage(gSystem->ExpandPathName(Form("$ALICE_ROOT/%s.par", module)));
1813             if (result<0) {
1814                ::Error("AnalysisTrainPWG4Jets.C::LoadLibrary", "Could not find module %s.par in current directory nor in $ALICE_ROOT", module);
1815                return kFALSE;
1816             }
1817          }   
1818          result = gProof->EnablePackage(module);
1819          break;
1820       default:
1821          return kFALSE;
1822    }         
1823    if (result < 0) {
1824       ::Error("AnalysisTrainPWG4Jets.C::LoadLibrary", "Could not load module %s", module);
1825       return kFALSE;
1826    }
1827    return kTRUE;
1828 }           
1829
1830
1831
1832 //______________________________________________________________________________
1833 Bool_t LoadSource(const char *source, const char *mode, Bool_t rec=kFALSE)
1834 {
1835 // Load a module library in a given mode. Reports success.
1836    Int_t imode = -1;
1837    Int_t result = -1;
1838    if (!strcmp(mode, "LOCAL")) imode = 0;
1839    if (!strcmp(mode, "PROOF")) imode = 1;
1840    if (!strcmp(mode, "GRID"))  imode = 2;
1841    TString ssource(source);
1842    TString basename = gSystem->BaseName(ssource.Data());
1843    if (!ssource.Length()) {
1844       ::Error("AnalysisTrainPWG4Jets.C::LoadSource", "Empty task name");
1845       return kFALSE;
1846    }   
1847    // we have a source code so compile it
1848    if (ssource.EndsWith(".cxx")) {
1849      // need to copy it here other wise the path is also used on grid...
1850      ssource.Remove(ssource.Index(".cxx"));
1851      basename.Remove(basename.Index(".cxx"));
1852      Printf("LoadSources:: Copying...  path %s{cxx,h}",ssource.Data());
1853      gSystem->Exec(Form("cp %s.cxx . ",ssource.Data()));
1854      gSystem->Exec(Form("cp %s.h . ",ssource.Data()));
1855      // Path to code
1856      // only needed for local compilation, in grid and proof mode 
1857      // the task headers are uploaded 
1858      //     path.Remove(path.Index(gSystem->BaseName(path.Data())));
1859      // Printf("LoadSources:: Including path %s",path.Data());
1860      //  if(path.Length()>0)gROOT->ProcessLine(Form(".include %s",path.Data()));
1861      Printf("LoadSources:: Loading...  path %s",basename.Data());
1862      switch (imode) {
1863      case 0:
1864        result = gROOT->LoadMacro(Form("%s.cxx++g",basename.Data()));
1865        break;
1866      case 1:
1867        result = gProof->LoadMacro(Form("%s.cxx++g",basename.Data()));
1868        break;
1869      case 2:
1870        result = gROOT->LoadMacro(Form("%s.cxx++g",basename.Data()));
1871        if (rec){
1872          // what we want to compile
1873          anaSources += Form("%s.cxx ",basename.Data()); 
1874          // what we need as input...
1875          anaLibs += Form("%s.cxx %s.h ",basename.Data(),basename.Data()); 
1876        }
1877        break;
1878      default:
1879        return kFALSE;
1880      }
1881    } 
1882    if (result < 0) {
1883       ::Error("AnalysisTrainPWG4Jets.C::LoadSources", "Could not load source %s", source);
1884       return kFALSE;
1885    }
1886    return kTRUE;
1887 }           
1888
1889
1890 //______________________________________________________________________________
1891 TChain *CreateChain(const char *mode, const char *plugin_mode)
1892 {
1893 // Create the input chain
1894    Int_t imode = -1;
1895    if (!strcmp(mode, "LOCAL")) imode = 0;
1896    if (!strcmp(mode, "PROOF")) imode = 1;
1897    if (!strcmp(mode, "GRID"))  imode = 2;
1898    TChain *chain = NULL;
1899    // Local chain
1900    switch (imode) {
1901       case 0:
1902          if (iAODanalysis) {
1903             if (!kLocalXMLDataset.Length()) {
1904                // Local AOD
1905                chain = new TChain("aodTree");
1906                TString line;
1907                ifstream in;
1908                in.open(kLocalDataList.Data());
1909                Int_t ic = 0;
1910                while (in.good()) {
1911                  in >> line;
1912                  if (line.Length() == 0) continue;
1913                  Printf("%d adding %s",ic,line.Data());
1914                  chain->Add(line.Data());
1915                  ic++;
1916                }       
1917             } else {
1918                // Interactive AOD
1919                chain = CreateChainSingle(kLocalXMLDataset, "aodTree");
1920             }
1921          } else {      
1922            if (!kLocalXMLDataset.Length()) {
1923              // Local ESD
1924              chain = new TChain("esdTree");
1925              TString line;
1926              ifstream in;
1927              in.open(kLocalDataList.Data());
1928              while (in.good()) {
1929                in >> line;
1930                if (line.Length() == 0) continue;
1931                cout << " line = " << line << endl;
1932                chain->Add(line.Data());
1933              }       
1934            } else {
1935              // Interactive ESD
1936                chain = CreateChainSingle(kLocalXMLDataset, "esdTree");
1937            }   
1938          }
1939          break;
1940       case 1:
1941          break;
1942       case 2:
1943          if (kPluginUse) {
1944 //            AliAnalysisGrid *alienHandler = CreateAlienHandler(plugin_mode);
1945 //            AliAnalysisManager::GetAnalysisManager()->SetGridHandler(alienHandler);
1946          } else {
1947             TString           treeName = "esdTree";
1948             if (iAODanalysis) treeName = "aodTree";
1949             chain = CreateChainSingle("wn.xml", treeName);
1950          }
1951          break;      
1952       default:   
1953    }
1954    if (chain && chain->GetNtrees()) return chain;
1955    return NULL;
1956 }   
1957
1958 //______________________________________________________________________________
1959 TChain* CreateChainSingle(const char* xmlfile, const char *treeName)
1960 {
1961    printf("*******************************\n");
1962    printf("*** Getting the ESD Chain   ***\n");
1963    printf("*******************************\n");
1964    TAlienCollection * myCollection  = TAlienCollection::Open(xmlfile);
1965
1966    if (!myCollection) {
1967       ::Error("AnalysisTrainPWG4Jets.C::CreateChainSingle", "Cannot create an AliEn collection from %s", xmlfile) ;
1968       return NULL ;
1969    }
1970
1971    TChain* chain = new TChain(treeName);
1972    myCollection->Reset() ;
1973    while ( myCollection->Next() ) chain->Add(myCollection->GetTURL("")) ;
1974    chain->ls();
1975    return chain;
1976 }
1977
1978 //______________________________________________________________________________
1979 Int_t SetupPar(char* pararchivename)
1980 {
1981    if (!pararchivename || !strlen(pararchivename)) return -1;
1982    char processline[1024];
1983    if (gSystem->AccessPathName(Form("%s.par", pararchivename))) {
1984       if (!gSystem->AccessPathName(Form("%s/%s.par", gSystem->Getenv("ALICE_ROOT"),pararchivename))) {
1985          ::Info("AnalysisTrainPWG4Jets.C::SetupPar", "Getting %s.par from $ALICE_ROOT", pararchivename);
1986         TFile::Cp(gSystem->ExpandPathName(Form("$ALICE_ROOT/%s.par", pararchivename)), 
1987                   Form("%s.par",pararchivename));
1988       } else {
1989          ::Error("AnalysisTrainPWG4Jets.C::SetupPar", "Cannot find %s.par", pararchivename);
1990          return -1;
1991       }   
1992    }
1993    if (kPluginUse && kSaveTrain) gSystem->Exec(Form("ln -s ../%s.par %s",pararchivename, kTrainName.Data()));
1994    gSystem->Exec(Form("tar xvzf %s.par", pararchivename));
1995
1996    TString ocwd = gSystem->WorkingDirectory();
1997    if (!gSystem->ChangeDirectory(pararchivename)) return -1;
1998         
1999    // check for BUILD.sh and execute
2000    if (!gSystem->AccessPathName("PROOF-INF/BUILD.sh")) {
2001       printf("*******************************\n");
2002       printf("*** Building PAR archive    ***\n");
2003       printf("*******************************\n");          
2004       if (gSystem->Exec("PROOF-INF/BUILD.sh")) {
2005          Error("runProcess","Cannot Build the PAR Archive! - Abort!");
2006          return -1;
2007       }
2008    }
2009
2010         // check for SETUP.C and execute
2011         if (!gSystem->AccessPathName("PROOF-INF/SETUP.C")) {
2012             printf("*******************************\n");
2013             printf("*** Setup PAR archive       ***\n");
2014             printf("*******************************\n");
2015             gROOT->Macro("PROOF-INF/SETUP.C");
2016         }       
2017         if (!gSystem->ChangeDirectory(ocwd.Data())){
2018           Error("Change back directory",Form("Cannot change to %s",ocwd.Data()));
2019           return -1;
2020         }
2021    return 0;
2022 }
2023
2024 //______________________________________________________________________________
2025 AliAnalysisAlien* CreateAlienHandler(const char *plugin_mode)
2026 {
2027 // Check if user has a valid token, otherwise make one. This has limitations.
2028 // One can always follow the standard procedure of calling alien-token-init then
2029 //   source /tmp/gclient_env_$UID in the current shell.
2030 //   if (!AliAnalysisGrid::CreateToken()) return NULL;
2031    AliAnalysisAlien *plugin = new AliAnalysisAlien();
2032 // Set the run mode (can be "full", "test", "offline", "submit" or "terminate")
2033    plugin->SetRunMode(plugin_mode);
2034    if (kPluginUseProductionMode) plugin->SetProductionMode();
2035    plugin->SetJobTag(kJobTag);
2036    plugin->SetNtestFiles(1);
2037 //   plugin->SetPreferedSE("ALICE::NIHAM::File");
2038 // Set versions of used packages
2039    plugin->SetAPIVersion("V1.1x");
2040    //   plugin->SetAPIVersion("V1.0x");
2041 //   plugin->SetAPIVersion("V2.4");
2042    plugin->SetROOTVersion(kPluginRootVersion);
2043    plugin->SetAliROOTVersion(kPluginAliRootVersion);
2044 // Declare input data to be processed.
2045 // Method 1: Create automatically XML collections using alien 'find' command.
2046 // Define production directory LFN
2047    plugin->SetGridDataDir(kGridDatadir.Data());
2048 // Set data search pattern
2049    if (iAODanalysis) plugin->SetDataPattern(Form(" %s/*/*AliAOD.root",kGridPassPattern.Data()));
2050    else              plugin->SetDataPattern(Form(" %s/*/*AliESDs.root",kGridPassPattern.Data()));
2051 // ...then add run numbers to be considered
2052 //   plugin->SetRunRange(kGridRunRange[0], kGridRunRange[1]);
2053    for (Int_t i=kGridRunRange[0]; i<=kGridRunRange[1]; i++) {
2054      Printf("AnalysisTrainPWG4Jets Adding run number %s", Form(kGridRunPattern.Data(),i));
2055      plugin->AddRunNumber(Form(kGridRunPattern.Data(),i));
2056    }   
2057
2058    if(kGridLocalRunList.Length()>0){
2059      ifstream in1;
2060      in1.open(kGridLocalRunList.Data());
2061      int iRun;
2062      int icount = 0;
2063      Int_t nRun = 0;
2064      // just use run numbers, negatives will be excluded
2065      while(in1>>iRun){
2066        if(iRun>=0){
2067          if(iRun>=0&&nRun>=kGridOffsetRunFromList&&(nRun<kGridMaxRunsFromList)){
2068            Printf("AnalysisTrainPWG4Jets Adding run number from File %d: %s",nRun,Form(kGridRunPattern.Data(),iRun));
2069            plugin->AddRunNumber(Form(kGridRunPattern.Data(),iRun));
2070
2071          }
2072          else{
2073            Printf("AnalysisTrainPWG4Jets Skipping run number from File %d: %d",nRun, iRun);
2074          }
2075          nRun++;
2076        }
2077        else{
2078          Printf("AnalysisTrainPWG4Jets Skipping run number from File %d: %d",nRun, iRun);
2079        }
2080      }
2081    }
2082 // Method 2: Declare existing data files (raw collections, xml collections, root file)
2083 // If no path mentioned data is supposed to be in the work directory (see SetGridWorkingDir())
2084 // XML collections added via this method can be combined with the first method if
2085 // the content is compatible (using or not tags)
2086 //   plugin->AddDataFile("tag.xml");
2087 //   plugin->AddDataFile("/alice/data/2008/LHC08c/000057657/raw/Run57657.Merged.RAW.tag.root");
2088 // Define alien work directory where all files will be copied. Relative to alien $HOME.
2089    TString alien_workdir = "";
2090    
2091    if (iAODanalysis)  alien_workdir += "analysisAOD";
2092    else               alien_workdir += "analysisESD";    
2093        if(kGridDataSet.Length()>0)alien_workdir += Form("/%s%s",kGridDataSet.Data(),kGridExtraAliendirLevel.Data());
2094    plugin->SetGridWorkingDir(alien_workdir.Data());
2095
2096    // Declare alien output directory. Relative to working directory.
2097    if (!kGridOutdir.Length()) kGridOutdir = Form("output_%s",kTrainName.Data());
2098    plugin->SetGridOutputDir(kGridOutdir);
2099
2100    // Add external packages
2101    plugin->AddExternalPackage("boost::v1_43_0");
2102    plugin->AddExternalPackage("cgal::v3.6");
2103    plugin->AddExternalPackage("fastjet::v2.4.2");
2104
2105
2106    // set extra libs before par file compilation
2107    anaLibs += kGridExtraFiles;
2108    anaLibs     = anaLibs.Strip();   
2109    Printf("anaLibs %s",anaLibs.Data());
2110    Printf("anaLibsExtra %s",anaLibsExtra.Data());
2111
2112    if (anaLibs.Length())          plugin->SetAdditionalLibs(anaLibs.Data());
2113    if (anaLibsExtra.Length())     plugin->SetAdditionalRootLibs(anaLibsExtra.Data());
2114
2115    TString ana_sources = "";
2116    TString ana_add = "";
2117    if (kUsePAR && anaPars.Length()) {
2118       printf("%s\n", anaPars.Data());
2119       TObjArray *arr;
2120       TObjString *objstr;
2121       arr = anaPars.Tokenize(" ");
2122       TIter next(arr);
2123       while ((objstr=(TObjString*)next())) plugin->EnablePackage(objstr->GetString());
2124       delete arr;
2125    } 
2126    
2127 // Declare the analysis source files names separated by blancs. To be compiled runtime
2128 // using ACLiC on the worker nodes.
2129    ana_sources = anaSources.Strip();
2130 // Declare all libraries (other than the default ones for the framework. These will be
2131 // loaded by the generated analysis macro. Add all extra files (task .cxx/.h) here.
2132
2133    if (ana_sources.Length()) plugin->SetAnalysisSource(ana_sources);
2134    plugin->SetExecutableCommand(kPluginExecutableCommand.Data());  
2135    // Declare the output file names separated by blancs.
2136    // (can be like: file.root or file.root@ALICE::Niham::File)
2137    plugin->SetMergeExcludes(kGridMergeExclude);
2138    plugin->SetMaxMergeFiles(kGridMaxMergeFiles);
2139    plugin->SetNrunsPerMaster(kGridRunsPerMaster);
2140    plugin->SetMergeViaJDL(kPluginMergeViaJDL);
2141    // Use fastread option
2142    plugin->SetFastReadOption(kPluginFastReadOption);
2143    // UseOverwrite mode
2144    plugin->SetOverwriteMode(kPluginOverwriteMode); 
2145    // Optionally define the files to be archived.
2146    //   plugin->SetOutputArchive("log_archive.zip:stdout,stderr@ALICE::NIHAM::File root_archive.zip:AliAOD.root,AOD.tag.root@ALICE::NIHAM::File");
2147    plugin->SetOutputToRunNo(kPluginOutputToRunNumber);     // write the output to subdirs named after run number
2148    
2149    // Put default output files to archive
2150    TString listhists = "";
2151    TString listaods  = "";
2152    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
2153    TIter next(mgr->GetOutputs());
2154    AliAnalysisDataContainer *output;
2155    while ((output=(AliAnalysisDataContainer*)next())) {
2156       const char *filename = output->GetFileName();
2157       if (!(strcmp(filename, "default"))) {
2158         if (!mgr->GetOutputEventHandler()) continue;
2159          filename = mgr->GetOutputEventHandler()->GetOutputFileName();
2160          if (listaods.Length()) listaods += " ";
2161          listaods += filename;
2162       } else {
2163         if(!listhists.Contains(filename)){
2164           if (listhists.Length()) listhists += " ";
2165           listhists += filename;
2166         }
2167       }
2168    }
2169
2170    if (mgr->GetExtraFiles().Length()) {
2171      if (listaods.Length()) listaods += " ";
2172      listaods += mgr->GetExtraFiles();
2173    }
2174
2175    // if we do not fill the aod we do not need to store it
2176    //   kGridMergeExclude = listaods;
2177    
2178    if(kSaveAOD>=0){
2179      TString outputFiles =  "";
2180      outputFiles += mgr->GetExtraFiles();
2181      if (listhists.Length()) outputFiles += " ";
2182      outputFiles += listhists;
2183      plugin->SetDefaultOutputs(kFALSE);
2184      Printf("%s:%d Starting with the files %s",(char*)__FILE__,__LINE__,outputFiles.Data());
2185      // remove
2186      // no harm done when we try to remove something that is not there :)
2187      if(!(kSaveAOD&(1<<0))){
2188        outputFiles.ReplaceAll("AliAOD.root ","");
2189        listaods.ReplaceAll("AliAOD.root ","");
2190      }
2191      if(!(kSaveAOD&(1<<1))){
2192        if(kDeltaAODJetName.Length())outputFiles.ReplaceAll(kDeltaAODJetName.Data(),"");
2193        if(kDeltaAODJetName.Length())listaods.ReplaceAll(kDeltaAODJetName.Data(),"");
2194        
2195      }
2196      if(!(kSaveAOD&(1<<2))){
2197        if(kDeltaAODPartCorrName.Length())outputFiles.ReplaceAll(kDeltaAODPartCorrName.Data(),"");
2198        if(kDeltaAODPartCorrName.Length())listaods.ReplaceAll(kDeltaAODPartCorrName.Data(),"");
2199      }
2200      if(!(kSaveAOD&(1<<3))){
2201        if(kDeltaAODJCORRANName.Length())outputFiles.ReplaceAll(kDeltaAODJCORRANName.Data(),"");
2202        if(kDeltaAODJCORRANName.Length())listaods.ReplaceAll(kDeltaAODJCORRANName.Data(),"");
2203      }
2204      
2205      // 
2206      plugin->SetDefaultOutputs(kFALSE);
2207      Printf("%s:%d Saving the files %s",(char*)__FILE__,__LINE__,outputFiles.Data());
2208      plugin->SetOutputFiles(outputFiles.Data());
2209    }
2210
2211    TString outputArchive;
2212    outputArchive = Form("log_archive.zip:std*@%s","disk=1");
2213    listaods.ReplaceAll(" ", ",");
2214    listhists.ReplaceAll(" ", ",");
2215    if (listhists.Length()){
2216      outputArchive += " ";
2217      outputArchive += "root_archive.zip:";
2218      outputArchive += listhists;
2219      if (listaods.Length()){
2220        outputArchive += ",";
2221        outputArchive += listaods;
2222      }
2223      outputArchive += Form("@%s", kGridOutputStorages.Data());
2224    }
2225    else{
2226      
2227      if (listaods.Length()){
2228        // we have only aod'ish output
2229        outputArchive += " ";
2230        outputArchive += "root_archive.zip:";
2231        outputArchive += listaods;
2232        outputArchive += Form("@%s", kGridOutputStorages.Data());
2233      }
2234      else{
2235        // no other outputs than std..
2236       ::Fatal("AnalysisTrainPWG4Jets", "No task output !");
2237      }
2238    }
2239
2240    plugin->SetDefaultOutputs(kFALSE);
2241    plugin->SetOutputArchive(outputArchive);
2242
2243
2244    // Optionally set a name for the generated analysis macro (default MyAnalysis.C)
2245    plugin->SetAnalysisMacro(Form("%s.C", kTrainName.Data()));
2246    // Optionally set maximum number of input files/subjob (default 100, put 0 to ignore)
2247    plugin->SetSplitMaxInputFileNumber(kGridFilesPerJob);
2248    // Optionally set number of failed jobs that will trigger killing waiting sub-jobs.
2249    //   plugin->SetMaxInitFailed(5);
2250    // Optionally resubmit threshold.
2251    // plugin->SetMasterResubmitThreshold(90);
2252    // Optionally set time to live (default 30000 sec)
2253    plugin->SetTTL(54000); // 15h...
2254    // Optionally set input format (default xml-single)
2255    plugin->SetInputFormat("xml-single");
2256    // Optionally modify the name of the generated JDL (default analysis.jdl)
2257    plugin->SetJDLName(Form("%s.jdl", kTrainName.Data()));
2258    // Optionally modify the executable name (default analysis.sh)
2259    plugin->SetExecutable(Form("%s.sh", kTrainName.Data()));
2260    // Optionally modify job price (default 1)
2261    plugin->SetPrice(1);      
2262    // Optionally modify split mode (default 'se')    
2263    plugin->SetSplitMode("se");
2264    return plugin;
2265 }
2266
2267 //______________________________________________________________________________
2268 void WriteConfig()
2269 {
2270 // Write train configuration in a file. The file name has the format:
2271 // train_[trainName]_ddMonthyyyy_time.C
2272    if (kUseDate) {
2273       gSystem->Exec("date +%d%b%Y_%Hh%M > date.tmp");
2274       ifstream fdate("date.tmp");
2275       if (!fdate.is_open()) {
2276          ::Error("AnalysisTrainPWG4Jets.C::Export","Could not generate file name");
2277          return;
2278       }
2279       const char date[64];
2280       fdate.getline(date,64);
2281       fdate.close();
2282       gSystem->Exec("rm date.tmp");
2283       kTrainName = Form("train_%s_%s", kTrainName.Data(), date);
2284    } else {
2285       kTrainName = Form("train_%s", kTrainName.Data());
2286    }   
2287    TString cdir = gSystem->WorkingDirectory();
2288    gSystem->MakeDirectory(kTrainName);
2289    gSystem->ChangeDirectory(kTrainName);
2290    ofstream out;
2291    out.open(Form("%sConfig.C",kTrainName.Data()), ios::out); 
2292    if (out.bad()) {
2293       ::Error("AnalysisTrainPWG4Jets.C::Export", "Cannot open ConfigTrain.C for writing");
2294       return;
2295    }
2296    out << "{" << endl;
2297    out << "   kTrainName      = " << "\"" << kTrainName.Data() << "\";" << endl;
2298    out << "   kProofCluster   = " << "\"" << kProofCluster.Data() << "\";" << endl;
2299    out << "   kProofUseAFPAR        = " << kProofUseAFPAR << ";" << endl;
2300    if (kProofUseAFPAR) 
2301       out << "   kProofAFversion       = " << kProofAFversion.Data() << ";" << endl;
2302    out << "   kProofDataSet   = " << "\"" << kProofDataSet.Data() << "\";" << endl;
2303    out << "   kPluginUse       = " << kPluginUse << ";" << endl;
2304    out << "   kUsePAR          = " << kUsePAR << ";" << endl;
2305    out << "   kUseCPAR         = " << kUseCPAR << ";" << endl;
2306    out << "   kPluginRootVersion    = " << "\"" << kPluginRootVersion.Data() << "\";" << endl;
2307    out << "   kPluginAliRootVersion = " << "\"" << kPluginAliRootVersion.Data() << "\";" << endl;
2308    out << "   kGridDatadir   = " << "\"" << kGridDatadir.Data() << "\";" << endl;
2309    if (!kGridOutdir.Length()) kGridOutdir = Form("output_%s",kTrainName.Data());
2310    out << "   kGridOutdir    = " << "\"" << kGridOutdir.Data() << "\";" << endl;
2311    out << "   kGridMaxMergeFiles   = " << kGridMaxMergeFiles << ";" << endl;
2312    out << "   kGridMergeExclude    = " << "\"" << kGridMergeExclude.Data() << "\";" << endl;
2313    out << "   kGridRunsPerMaster  = " << kGridRunsPerMaster << ";" << endl;
2314    out << "   kGridFilesPerJob    = " << kGridFilesPerJob << ";" << endl;
2315    out << "   kGridRunRange[0]    = " << kGridRunRange[0] << ";" << endl;
2316    out << "   kGridRunRange[1]    = " << kGridRunRange[1] << ";" << endl;
2317    out << "   kUseDebug          = " << kUseDebug << ";" << endl;
2318    out << "   kUseMC           = " << kUseMC << ";" << endl;
2319    out << "   kUseESDTags         = " << kUseESDTags << ";" << endl;
2320    out << "   kUseKinefilter      = " << kUseKinefilter << ";" << endl;
2321    out << "   kUseTR           = " << kUseTR << ";" << endl;
2322    out << "   kUseAODTags      = " << kUseAODTags << ";" << endl;
2323    out << "   kSaveTrain       = " << "kFALSE;" << endl << endl;
2324    out << "   // Analysis modules" << endl;
2325    out << "   iAODanalysis    = " << iAODanalysis << ";" << endl;
2326    out << "   iAODhandler     = " << iAODhandler << ";" << endl;
2327    out << "   iESDfilter      = " << iESDfilter << ";" << endl;
2328    out << "   iJETAN          = " << iJETAN << ";" << endl;
2329    out << "// Configuration fot the wagons" << endl;
2330    out << "}" << endl;
2331    ::Info("AnalysisTrainPWG4Jets.C::WriteConfig", "Train configuration wrote to file %s", Form("config_%s.C", kTrainName.Data()));
2332    gSystem->ChangeDirectory(cdir);
2333 }   
2334
2335 //______________________________________________________________________________
2336 Bool_t LoadConfig(const char *filename)
2337 {
2338 // Read train configuration from file
2339    if (gSystem->AccessPathName(filename)) {
2340       ::Error("AnalysisTrainPWG4Jets.C::LoadConfig", "Config file name not found");
2341       return kFALSE;
2342    }   
2343    gROOT->ProcessLine(Form(".x %s", filename));
2344    ::Info("AnalysisTrainPWG4Jets.C::LoadConfig", "Train configuration loaded from file %s", filename);
2345    return kTRUE;
2346 }
2347
2348 Bool_t PatchJDL(){
2349   Printf(">>> Patching JDL");
2350   AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
2351   AliAnalysisAlien*    gridHandler = (AliAnalysisAlien*)mgr->GetGridHandler();
2352   TGridJDL *jdl = gridHandler->GetGridJDL();
2353   if(iJETAN)jdl->AddToPackages("fastjet","v2.4.0");
2354   gridHandler->WriteJDL(kFALSE);
2355   Printf("<<<  Patching JDL");
2356   return kTRUE;
2357 }
2358
2359 Bool_t PatchAnalysisMacro(){
2360   Printf(">>> Patching AnalysisMacro");
2361   gSystem->Exec(Form("mv %s.C %s.C_tmp",kTrainName.Data(),kTrainName.Data()));
2362
2363   ifstream in1; 
2364   in1.open(Form("%s.C_tmp", kTrainName.Data()));
2365   char cLine[250];
2366   TString st;
2367   while(in1.getline(cLine,250)){
2368     st += cLine;
2369     st += "\n";
2370   }
2371   Int_t index= -1;
2372   index = st.Index("gSystem->Load(\"libPhysics\");");
2373   index += strlen("gSystem->Load(\"libPhysics\");");
2374   /*
2375     TObjArray *arr;
2376     TObjString *objstr;
2377     arr = anaLibs.Tokenize(" ");
2378     TIter next(arr);
2379
2380     add += "\n\n // added by CKB \n";
2381     while ((objstr=(TObjString*)next())){
2382       if(objstr->GetString().Contains("PWG3"))continue;
2383       if(objstr->GetString().EndsWith(".so"))add += Form("gSystem->Load(\"%s\");\n",objstr->GetString().Data());
2384     }
2385     delete arr; 
2386     */
2387     //    add += Form("AliLog::SetGlobalLogLevel(%d);\n",AliLog::GetGlobalLogLevel());
2388   TString add = "";
2389
2390   if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);
2391   add += "\n\n // added by CKB \n";
2392   if(kErrorIgnoreLevel>0)add += Form("gErrorIgnoreLevel = %d;\n",kErrorIgnoreLevel);
2393   add += "\n gSystem->AddIncludePath(\"./\"); \n";
2394   add += "\n gSystem->SetFPEMask(); \n";
2395
2396
2397   if(gGrid&&kPluginAliRootVersion.Length()==0){
2398     /*
2399     add += "\n // Dirty hack for TRD reference data \n";
2400     add += "\n gSystem->Setenv(\"ALICE_ROOT\",\"";
2401     add += Form("alien://%s/rootfiles/",gGrid->GetHomeDirectory());
2402     add += "\"); \n";
2403     */
2404   }
2405
2406   add += "// BKC \n\n";
2407   st.Insert(index,add.Data());
2408
2409   if(kUseDebug){
2410     //    st.Insert(index,"\n gROOT->ProcessLine(\".trace\"); // CKB \n");
2411   }
2412
2413   if(kUseCPAR&&kPluginAliRootVersion.Length()==0){
2414     index = st.Index("gSystem->AddIncludePath(\"-I$"); // uncommen $ALICE_ROOT include for par files
2415     if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);
2416     st.Insert(index,"// CKB comment out whehn no aliroot is provided \n //");
2417   }
2418
2419   if(AliLog::GetGlobalLogLevel()==AliLog::kFatal){
2420     index = st.Index("AliLog::SetGlobal"); // ncomment setting of log level, do my own
2421     if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);
2422     st.Insert(index,"AliLog::SetGlobalLogLevel(AliLog::kFatal);// CKB \n  // CKB comment out for own setting \n  //");
2423   }
2424
2425   ofstream out;
2426   out.open(Form("%s.C", kTrainName.Data()));
2427   if (out.bad()) {
2428     return kFALSE;
2429   }
2430   out << st << endl;
2431   Printf("<<< Patching AnalysisMacro");
2432
2433
2434
2435
2436
2437   Printf(">>> Patching Merge Macro");
2438   gSystem->Exec(Form("mv %s_merge.C %s_merge.C_tmp",kTrainName.Data(),kTrainName.Data()));
2439
2440   ifstream in2; 
2441   in2.open(Form("%s_merge.C_tmp", kTrainName.Data()));
2442   TString st2;
2443   while(in2.getline(cLine,250)){
2444     st2 += cLine;
2445     st2 += "\n";
2446   }
2447   index = st2.Index("gSystem->Load(\"libPhysics\");");
2448   index += strlen("gSystem->Load(\"libPhysics\");");
2449   TString add2 = "";
2450   add2 += "\n gSystem->AddIncludePath(\"./\"); \n";
2451   if(gGrid&&kPluginAliRootVersion.Length()==0){
2452     /*
2453     add2 += "\n // Dirty hack for TRD reference data \n";
2454     add2 += "\n gSystem->Setenv(\"ALICE_ROOT\",\"";
2455     add2 += Form("alien://%s/rootfiles/",gGrid->GetHomeDirectory());
2456     add2 += "\"); \n";
2457     */
2458   }
2459   add2 += "// BKC \n\n";
2460   if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);
2461   st2.Insert(index,add.Data());
2462
2463
2464   if(kUseDebug){
2465     //    st2.Insert(index,"\n gROOT->ProcessLine(\".trace\"); // CKB \n");
2466   }
2467
2468   if(kUseCPAR&&kPluginAliRootVersion.Length()==0){
2469     index = st2.Index("gSystem->AddIncludePath(\"-I$"); // uncomment $ALICE_ROOT include for par files
2470     if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);
2471     st2.Insert(index,"// CKB comment out whehn no aliroot is provided \n //");
2472   }
2473
2474   // do not exclude the extra files from merign, this is done explicitly in this train script
2475   //  index = st2.Index("mergeExcludes +="); // uncommen $ALICE_ROOT include for par files
2476   //  if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);
2477   // st2.Insert(index,"// CKB comment out, handled explicitly by the train macro \n //");
2478
2479
2480   ofstream out2;
2481   out2.open(Form("%s_merge.C", kTrainName.Data()));
2482   if (out2.bad()) {
2483     return kFALSE;
2484   }
2485   out2 << st2 << endl;
2486   Printf("<<< Patching Merging Macro");
2487
2488
2489
2490   return kTRUE;
2491
2492 }