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