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