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