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