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