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