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