setting the eta range for clustered tracks, adding the correct signature for backgrou...
[u/mrichter/AliRoot.git] / PWG4 / macros / AnalysisTrainPWG4.C
1 // =============================================================================
2 // ### General Steering variables
3 // =============================================================================
4 //== general setup variables
5 TString     kTrainName         = "testAnalysis"; // *CHANGE ME* (no blancs or special characters)
6 TString     kJobTag            = "PWG4 Analysis train configured"; // *CHANGE ME*
7
8
9 // Usage of par files ONLY in grid mode and ONLY if the code is not available
10 // in the deployed AliRoot versions. Par file search path: local dir, if not there $ALICE_ROOT.
11 // To refresh par files, remove the ones in the workdir, then do "make <target.par>" in 
12 // AliRoot.
13 Bool_t      kUsePAR             = kFALSE;  // use par files for extra libs
14 Bool_t      kUseCPAR            = kFALSE;  // use par files for common libs
15 Bool_t      kFillAOD = kFALSE;  // switch of AOD filling for on the fly analysis
16 Int_t       kSaveAOD = 8;        // Bit switch 1 = Full AOD 2 = Jet AOD , 4 = PartCorr, 8 = JCORRAN 
17
18
19 //== general input and output variables
20 Int_t       iAODanalysis       = 0;      // Analysis on input AOD's
21 Int_t       iAODhandler        = 1;      // Analysis produces an AOD or dAOD's
22 Int_t       iCentralitySelection  = 0;      // Use the centrality
23 Int_t       iESDfilter         = 0;      // ESD to AOD filter (barrel + muon tracks)
24 Int_t       iPhysicsSelection  = 1;      // ESD to AOD filter (barrel + muon tracks)
25 UInt_t      iPhysicsSelectionFlag = 0; // set by pyshics selection and passed to the task, kMB, kUserDefined etc
26 Bool_t      useTender           = kFALSE; // use tender wagon 
27 Bool_t      kUseKinefilter     = kFALSE; // use Kinematics filter
28 Bool_t      kUseMuonfilter     = kFALSE; //
29 TString     kCommonOutputFileName = "PWG4_JetTasksOutput.root";
30 TString     kCaloQAOutputFileName = "PWG4_CaloQAOutput.root";
31
32 //== general process variables
33
34 // ### Other flags to steer the analysis
35 //==============================================================================
36 Bool_t      kSkipTerminate      = kTRUE; // Do not call Teminate
37 Bool_t      kUseDate            = kFALSE; // use date in train name
38 Bool_t      kUseDebug           = kTRUE; // activate debugging
39 Int_t       kErrorIgnoreLevel = -1; // takes the errror print level from .rootrc 
40 // From TError.h:
41 // const Int_t kUnset    =  -1;
42 // const Int_t kPrint    =   0;
43 // const Int_t kInfo     =   1000;
44 // const Int_t kWarning  =   2000;
45 // const Int_t kError    =   3000;
46 // const Int_t kBreak    =   4000;
47 // const Int_t kSysError =   5000;
48 // const Int_t kFatal    =   6000; 
49 Int_t       kUseSysInfo         = 0; // activate debugging
50 Long64_t    kNumberOfEvents     = 1234567890; // number of events to process from the chain
51 Bool_t      kUseMC              = kFALSE;  // use MC info
52 Bool_t      kIsMC               = kFALSE;  // is MC info, if false it overwrites Use(AOD)MC
53 Bool_t      kUseAODMC           = kFALSE;  // use MC infA
54 Bool_t      kUseESDTags         = kFALSE; // use ESD tags for selection
55 Bool_t      kUseTR              = kFALSE;  // use track references
56 Bool_t      kUseAODTags         = kFALSE;  // use AOD tags
57 Bool_t      kSaveTrain          = kFALSE;  // save train configuration as: 
58 Bool_t      kIsPbPb             = kFALSE;  // Pb+Pb
59
60
61 // ### Analysis modules to be included. Some may not be yet fully implemented.
62 //==============================================================================
63 Int_t       iJETAN                 = 2;      // Jet analysis (PWG4) // 1 write standard 2 write non-standard jets, 3 wrtie both
64 TString     kDefaultJetBranch     = "";      // is currently set when filled (iJETAN or clusters)
65 TString     kDefaultJetBackgroundBranch     = "";      // is currently set when filled (jet clsuters
66 Int_t       iDIJETAN                = 1;
67 Int_t       iJETANLib             = 1;
68 Int_t       iPWG4JetTasks      = 0;      // all jet tasks flag for lib laoding
69 Int_t       iPWG4JetServices   = 1;      // jet spectrum analysis
70 Int_t       iPWG4JetSpectrum   = 1;      // jet spectrum analysis
71 Int_t       iPWG4JCORRAN       = 0;      // JCORRAN module
72 Int_t       iPWG4LeadingUE     = 1;      // Underlying Event analysis
73 Int_t       iPWG4Fragmentation = 1;      // Official Fragmentation
74 Int_t       iPWG4JetChem       = 0;      // Jet chemistry 
75 Int_t       iPWG4PtQAMC        = 0;      // Marta's QA tasks 
76 Int_t       iPWG4PtSpectra     = 1;      // Marta's QA tasks 
77 Int_t       iPWG4PtQATPC       = 0;      // Marta's QA tasks 
78 Int_t       iPWG4Cosmics       = 0;      // Marta's Cosmics Taks 
79 Int_t       iPWG4QGSep         = 0;          // Sona's QG Separation task
80 Int_t       iPWG4Minijet       = 0;      // Eva's Mini Jet Task cluster task 
81 Int_t       iPWG4KMeans        = 0;      // Andreas' KMeans task 
82 Int_t       iPWG4Cluster       = 1;      // 
83 Int_t       iEMCUtilLibs       = 0;      // Flag to satisfy dependence on EMC utils
84 Int_t       iPWG4PartCorrLibs  = 0;      // Gustavo's part corr analysis
85 Int_t       iPWG4PartCorr      = 1;      // Gustavo's part corr analysis
86 Int_t       iPWG4CaloQA        = 0;      // Gustavo's part corr analysis
87 Int_t       iPWG4JetCorr       = 0;     // Paul's jet corr analysis
88 Int_t       iPWG4Tagged        = 0;      // Gustavo's part corr analysis
89 Int_t       iPWG4omega3pi      = 0;      // Omega to 3 pi analysis (PWG4) 
90 Int_t       iPWG4GammaConvLib     = 0;      // Gamma Conversio
91 Int_t       iPWG4GammaConv     = 1;      // Gamma Conversio
92 Int_t       iPWG4CaloConv     = 0;      // Gamma Conversio
93 Int_t       kHighPtFilterMask  = 256;     // change depending on the used AOD Filter
94 TString     kDeltaAODJetName   = ""; // AliAOD.Jets.root";     
95 TString     kDeltaAODJCORRANName   = "AliAOD.JCORRAN.root";     
96 TString     kDeltaAODPartCorrName   = "AliAOD.PartCorr.root";     
97
98
99 //==============================================================================
100 // ### PROOF Steering varibales
101 //==============================================================================
102 //== proof setup variables
103 TString     kProofCluster      = "alicecaf.cern.ch";
104 Bool_t      kProofUseAFPAR     = kFALSE;  // use AF special par file
105 TString     kProofAFversion          = "AF-v4-17";
106 //== proof input and output variables
107 TString     kProofDataSet      = "/COMMON/COMMON/LHC09a4_run8100X#/esdTree";
108 Bool_t      kProofSaveToAlien   = kFALSE; // save proof outputs in AliEn train_[trainName]_ddMonthyyyy_time.C
109 TString     kProofOutdir       = "";
110 Bool_t      kProofClearPackages = kFALSE;
111 Int_t       kProofEvents = 10000;
112 Int_t       kProofOffset = 0;
113 //== proof process variables
114
115
116 //==============================================================================
117 // ### Grid plugin Steering varibiables
118 //==============================================================================
119 //== grid plugin setup variables
120 Bool_t      kPluginUse         = kTRUE;   // do not change
121 Bool_t      kPluginUseProductionMode  = kFALSE;   // use the plugin in production mode
122 TString     kPluginRootVersion       = "v5-27-06b";  // *CHANGE ME IF MORE RECENT IN GRID*
123 TString     kPluginAliRootVersion    = "v4-21-09-AN";  // *CHANGE ME IF MORE RECENT IN GRID*                                          
124 Bool_t      kPluginMergeViaJDL       = kTRUE;  // merge via JDL
125 Bool_t      kPluginFastReadOption   = kFALSE;  // use xrootd tweaks
126 Bool_t      kPluginOverwriteMode    = kTRUE;  // overwrite existing collections
127 Int_t       kPluginOutputToRunNumber = 1;     // write the output to subdirs named after run number
128 TString     kPluginExecutableCommand = "root -b -q";
129 // TString     kPluginExecutableCommand = "source /Users/kleinb/setup_32bit_aliroot_trunk_clean_root_trunk.sh; alienroot -b -q ";
130
131 // == grid plugin input and output variables
132 TString     kGridDataDir      = "/alice/data/2010/LHC10e/";
133 Int_t       kGridMaxRunsFromList = 999999999;
134 Int_t       kGridOffsetRunFromList = 0; // skip the first n runs from the list
135 TString     kGridLocalRunList = "";
136 TString     kGridOutdir       = ""; // AliEn output directory. If blank will become output_<kTrainName>
137 TString     kGridDataSet      = "LHC10e"; // sub working directory not to confuse different run xmls 
138 Int_t       kGridRunRange[2]       =  {127724, 127730}; // Set the run range
139 TString     kGridRunPattern        = "%09d"; // important for leading zeroes!!
140 TString     kGridPassPattern       = "pass1";
141 TString     kGridExtraFiles        = ""; // files that will be added to the input list in the JDL...
142 Int_t       kGridMaxMergeFiles      = 12; // Number of files merged in a chunk grid run range
143 TString     kGridMergeExclude       = "AliAOD.root"; // Files that should not be merged
144 TString     kGridOutputStorages      = "disk=2"; // Make replicas on the storages
145 // == grid process variables
146 Int_t       kGridRunsPerMaster     = 100; // Number of runs per master job
147 Int_t       kGridFilesPerJob       = 100; // Maximum number of files per job (gives size of AOD)
148
149 //==============================================================================
150 // ### Local Steering variables
151 //==============================================================================
152 //== local setup variables
153 //== local input and output variables
154 TString     kLocalXMLDataset   = ""; // Change local xml dataset for local interactive analysis
155 TString     kLocalDataList   = "local_deltaaod.txt"; // Change local xml dataset for local interactive analysis
156 // == local process variables
157
158 TString kPluginMode;
159
160
161 // Temporaries.
162 TString anaPars = "";
163 TString anaLibs = "";
164 TString anaLibsExtra = "";
165 TString anaSources = "";
166 // Function signatures
167 class AliAnalysisAlien;
168
169 //______________________________________________________________________________
170 void AnalysisTrainPWG4(const char *analysis_mode="local", 
171                            const char *plugin_mode="",
172                            const char *config_file="",Int_t iOffset = 0,Int_t iTotal = 0)
173 {
174 // Main analysis train macro. If a configuration file is provided, all parameters
175 // are taken from there but may be altered by CheckModuleFlags.
176
177   // these flag may be needed by the config file
178   kPluginMode = plugin_mode;
179   
180   if (strlen(config_file) && !LoadConfig(config_file)) return;
181   if(iTotal>0)kGridMaxRunsFromList = iTotal; // overwrites the settings from config file
182   if(iOffset)kGridOffsetRunFromList = iOffset;
183   if(iOffset)kProofOffset = iOffset;
184
185
186    TString smode(analysis_mode);
187    smode.ToUpper();
188    // Check compatibility of selected modules 
189    CheckModuleFlags(smode);
190    //     gROOT->ProcessLine(".trace");
191
192    printf("==================================================================\n");
193    printf("===========    RUNNING ANALYSIS TRAIN %s IN %s MODE   ==========\n", kTrainName.Data(),smode.Data());
194    printf("==================================================================\n");
195                               printf("=  Configuring analysis train for:                               =\n");
196    if (iAODanalysis) printf("=  AOD analysis                                                  =\n");
197    else                     printf("=  ESD analysis                                                  =\n");
198    if (iPhysicsSelection)   printf("=  Physics selection                                                =\n");
199    if(iCentralitySelection)printf("=  Centrality selection                                                =\n");
200    if (useTender)   printf("=  Using tender                                                =\n");
201    if (iESDfilter)   printf("=  ESD filter                                                    =\n");
202    if (iJETAN)       printf("=  Jet analysis                                                  =\n");
203    printf("==================================================================\n");
204
205    char *printMask = ":: %20s  %10d\n";
206    printf(printMask,"Fill AOD",(UInt_t)kFillAOD);
207    printf(printMask,"Save AOD", (UInt_t)kSaveAOD);
208    printf(printMask,"MC truth", (UInt_t)kUseMC);
209    printf(printMask,"KINE filter", (UInt_t)kUseKinefilter);
210    printf(printMask,"track refs", (UInt_t)kUseTR);
211    printf(printMask,"tags", (UInt_t)kUseESDTags);
212    printf(printMask,"AOD tags", (UInt_t)kUseAODTags);
213    printf(printMask,"debugging", (UInt_t)kUseDebug);
214    printf(printMask,"PAR files", (UInt_t)kUsePAR);
215    printf(printMask,"AliEn plugin", (UInt_t)kPluginUse);
216    printf(printMask,"PWG4 Fragmentation",iPWG4Fragmentation);
217    printf(printMask,"PWG4 Jet Chem",iPWG4JetChem);
218    printf(printMask,"PWG4 Jet tasks",iPWG4JetTasks);
219    printf(printMask,"PWG4 Jet Services",iPWG4JetServices);     
220    printf(printMask,"PWG4 Jet Spectrum",iPWG4JetSpectrum);
221    printf(printMask,"PWG4 JCORRAN",iPWG4JCORRAN);
222    printf(printMask,"PWG4 Leading UE",iPWG4LeadingUE); 
223    printf(printMask,"PWG4 Pt QA MC",iPWG4PtQAMC);
224    printf(printMask,"PWG4 Pt Spectra",iPWG4PtSpectra);
225    printf(printMask,"PWG4 Pt QA TPC",iPWG4PtQATPC);     
226    printf(printMask,"PWG4 Cosmics",iPWG4Cosmics);     
227    printf(printMask,"PWG4 QGSep",iPWG4QGSep);
228    printf(printMask,"PWG4 Minijet",iPWG4Minijet);
229    printf(printMask,"PWG4 KMeans",iPWG4KMeans);
230    printf(printMask,"PWG4 Cluster",iPWG4Cluster);
231    printf(printMask,"PWG4 Part Corr",iPWG4PartCorr);
232    printf(printMask,"PWG4 Calo QA",iPWG4CaloQA);
233    printf(printMask,"PWG4 Jet Corr",iPWG4JetCorr);
234    printf(printMask,"PWG4 JCORRAN",iPWG4JCORRAN);
235    printf(printMask,"PWG4 Tagged",iPWG4Tagged);
236    printf(printMask,"PWG4 omega to 3 pi ",iPWG4omega3pi);
237    printf(printMask,"PWG4 Gamma Conv",iPWG4GammaConv);
238    printf(printMask,"PWG4 Calo Conv",iPWG4CaloConv);
239    printf(printMask,"HighPt FilterMask",kHighPtFilterMask);    
240    
241    //==========================================================================
242    // Connect to back-end system
243    if (!Connect(smode)) {
244       ::Error("AnalysisTrain", "Could not connect to %s back-end", analysis_mode);
245       return;
246    }   
247
248    // Load common libraries and set include path
249    if (!LoadCommonLibraries(smode)) {
250       ::Error("AnalysisTrain", "Could not load common libraries");
251       return;
252    }
253
254
255     
256    // Make the analysis manager and connect event handlers
257    AliAnalysisManager *mgr  = new AliAnalysisManager("PWG4Train", "pwg4 mini train");
258    if (kCommonOutputFileName.Length()>0)mgr->SetCommonFileName(kCommonOutputFileName.Data());
259    if (kProofSaveToAlien) mgr->SetSpecialOutputLocation(kProofOutdir);
260    mgr->SetNSysInfo(0);
261    if (!strcmp(plugin_mode, "test")) mgr->SetNSysInfo(1);
262    if (kUseSysInfo)mgr->SetNSysInfo(kUseSysInfo);
263    mgr->SetSkipTerminate(kSkipTerminate);
264
265    // Load analysis specific libraries
266    if (!LoadAnalysisLibraries(smode)) {
267       ::Error("AnalysisTrain", "Could not load analysis libraries");
268      return;
269    }   
270
271    // Create input handler (input container created automatically)
272    if (iAODanalysis) {
273    // AOD input handler
274       AliAODInputHandler *aodH = new AliAODInputHandler();
275       mgr->SetInputEventHandler(aodH);
276       //      if (iPWG4JetTasks) aodH->AddFriend(Form("deltas/%s",kDeltaAODJetName.Data()));
277       //      if (iPWG4PartCorr) aodH->AddFriend(Form("deltas/%s"kDeltaAODJetName.Data()));
278    } else {   
279    // ESD input handler
280       AliESDInputHandler *esdHandler = new AliESDInputHandler();
281       if (kUseESDTags) esdHandler->SetReadTags();
282       esdHandler->SetReadFriends(kFALSE);
283       mgr->SetInputEventHandler(esdHandler);       
284       //      if(iPWG4PtQATPC&& !kTrainName.Contains("pass5"))esdHandler->SetActiveBranches("ESDfriend");
285
286    }
287
288    // Monte Carlo handler
289    if (kUseMC && !iAODanalysis) {
290       AliMCEventHandler* mcHandler = new AliMCEventHandler();
291       mgr->SetMCtruthEventHandler(mcHandler);
292       mcHandler->SetReadTR(kUseTR); 
293    }   
294    // AOD output container, created automatically when setting an AOD handler
295    if (iAODhandler) {
296       // AOD output handler
297       AliAODHandler* aodHandler   = new AliAODHandler();
298       aodHandler->SetOutputFileName("AliAOD.root");
299       aodHandler->SetFillAODforRun(kFillAOD);
300       //
301       mgr->SetOutputEventHandler(aodHandler);
302       AliAnalysisDataContainer * cout_aod = mgr->GetCommonOutputContainer();
303       cout_aod->SetSpecialOutput();
304    }
305    // Debugging if needed
306
307    if (kUseDebug){
308      mgr->SetDebugLevel(3);
309    }
310    if(kUseSysInfo>0){
311      mgr->RegisterExtraFile("syswatch.root");
312      if(kGridMergeExclude.Length())kGridMergeExclude += " ";
313      kGridMergeExclude += "syswatch.root";
314    }
315    else{
316      AliLog::SetGlobalLogLevel(AliLog::kError);
317    }
318
319
320    //==========================================================================
321    // Create the chain. In this example it is created only from ALIEN files but
322    // can be done to work in batch or grid mode as well.
323    TChain *chain = CreateChain(smode, plugin_mode);
324         
325    //==========================================================================
326    // Load the tasks configuration macros for all wagons. These files are supposed now to be
327    // in the current workdir, but in AliEn they will be in the file catalog, 
328    // mapped from AliRoot and pecified in the jdl input list.
329     
330    // For now connection to top input container and common AOD output container
331    // is done in this macro, but in future these containers will be connected
332    // from each task configuration macro.
333    
334    //                                                                                                                              
335    // Tender and supplies. Needs to be called for every event.                                                                     
336    //                                                                                                                              
337    if (useTender) {
338       gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/TenderSupplies/AddTaskTender.C");
339       AliAnalysisTaskSE *tender = AddTaskTender(kTRUE);
340       //      tender->SelectCollisionCandidates();                                                                                      
341       tender->SetDebugLevel(2);
342    }
343
344
345
346    if(iPhysicsSelection && !iAODanalysis){
347      gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPhysicsSelection.C");
348      Bool_t rejectBkg = true;
349      if(kIsPbPb){
350        rejectBkg = false; // for the moment...
351      }
352      AliPhysicsSelectionTask* physSelTask = AddTaskPhysicsSelection(kIsMC,rejectBkg);  
353      iPhysicsSelectionFlag = AliVEvent::kMB;
354    }
355
356    if(iCentralitySelection){
357
358      // has to run before AOD filter
359      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskCentralitySelection.C");
360      const char* file1="$ALICE_ROOT/ANALYSIS/macros/AliCentralityBy1D_137161_v5.root";
361      const char* file2="$ALICE_ROOT/ANALYSIS/macros/AliCentralityBy1D_137366_v3.root";
362      AliCentralitySelectionTask *taskC = AddTaskCentralitySelection(file1,file2);
363       if (!taskC) ::Warning("AnalysisTrainPWG4", "AliCentralitySelectionTask cannot run for this train conditions - EXCLUDED");
364    }
365
366    if (iESDfilter && !iAODanalysis) {
367       //  ESD filter task configuration.
368       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskESDFilterPWG4Train.C");
369       AliAnalysisTaskESDfilter *taskesdfilter = AddTaskESDFilter(kUseKinefilter,kUseMuonfilter);
370       taskesdfilter->SetEnableFillAOD(kFALSE);
371
372       if(kIsMC){
373         mgr->RegisterExtraFile("pyxsec_hists.root");
374         if(kGridMergeExclude.Length())kGridMergeExclude += " ";
375         kGridMergeExclude += "pyxsec_hists.root";
376
377       }
378    }   
379
380    // AOD tags
381    if (kUseAODTags) {
382       AliAnalysisTaskTagCreator* tagTask = new AliAnalysisTaskTagCreator("AOD Tag Creator");
383       mgr->AddTask(tagTask);
384       AliAnalysisDataContainer *coutTags = mgr->CreateContainer("cTag",  TTree::Class(), 
385                                            AliAnalysisManager::kOutputContainer, "AOD.tag.root");
386       mgr->ConnectInput (tagTask, 0, mgr->GetCommonInputContainer());
387       mgr->ConnectOutput(tagTask, 1, coutTags);
388    }   
389     
390     // Jet analysis
391    if (iJETAN) {
392       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJets.C");
393       AliAnalysisTaskJets *taskjets = 0;
394       if(iJETAN&1){
395         // default nothing...
396       }
397       if(iJETAN&2){
398         // Set only few jet finders  backgroudn subtraction w an wo 
399         
400         taskjets = AddTaskJets("AOD","UA1",0.4,kHighPtFilterMask,1,0);     // high p_T no abackground subtraction
401         if(kDeltaAODJetName.Length()>0)taskjets->SetNonStdOutputFile(kDeltaAODJetName.Data());
402         taskjets = AddTaskJets("AOD","UA1",0.4,kHighPtFilterMask,1,1);     // high p_T abackground subtraction
403         if(kDeltaAODJetName.Length()>0)taskjets->SetNonStdOutputFile(kDeltaAODJetName.Data());
404         taskjets = AddTaskJets("AOD","UA1",0.2,kHighPtFilterMask,1,0);     // high p_T no abackground subtraction
405         if(kDeltaAODJetName.Length()>0)taskjets->SetNonStdOutputFile(kDeltaAODJetName.Data());
406         taskjets = AddTaskJets("AOD","UA1",0.2,kHighPtFilterMask,1,1);     // high p_T abackground subtraction
407         if(kDeltaAODJetName.Length()>0)taskjets->SetNonStdOutputFile(kDeltaAODJetName.Data());
408       }
409       if (!taskjets) ::Warning("AnalysisTrainPWG4", "AliAnalysisTaskJets cannot run for this train conditions - EXCLUDED");
410       if(kDeltaAODJetName.Length()>0)mgr->RegisterExtraFile(kDeltaAODJetName.Data()); 
411    }
412
413    if(iPWG4Cluster){
414      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetCluster.C");
415      AliAnalysisTaskJetCluster *taskCl = 0;
416      Float_t fCenUp = 0;
417      Float_t fCenLo = 0;
418      if(kIsPbPb&&!kIsMC){
419        fCenLo = 0;
420        fCenUp = 80;
421      }
422      if(iPWG4Cluster&1){
423
424        if(kIsPbPb){
425          taskCl = AddTaskJetCluster("AOD","",kHighPtFilterMask,iPhysicsSelectionFlag,"KT",0.4,0,1, kDeltaAODJetName.Data(),0.15); // this one is for the background and random jets
426          taskCl->SetBackgroundCalc(kTRUE);
427          taskCl->SetCentralityCut(fCenLo,fCenUp);
428          taskCl->SetGhostEtamax(0.9);
429          kDefaultJetBackgroundBranch = Form("%s_%s",AliAODJetEventBackground::StdBranchName(),taskCl->GetJetOutputBranch());
430          
431          taskCl = AddTaskJetCluster("AOD","",kHighPtFilterMask,iPhysicsSelectionFlag,"KT",0.2,0,1, kDeltaAODJetName.Data(),0.15); // this one is for the background and random jets
432          taskCl->SetBackgroundCalc(kTRUE);
433          taskCl->SetCentralityCut(fCenLo,fCenUp);
434          taskCl->SetGhostEtamax(0.9);
435        }
436        else{
437          taskCl = AddTaskJetCluster("AOD","",kHighPtFilterMask,iPhysicsSelectionFlag,"KT",0.6,0,1,kDeltaAODJetName.Data()); 
438          taskCl->SetBackgroundCalc(kTRUE);
439          kDefaultJetBackgroundBranch = Form("%s_%s",AliAODJetEventBackground::StdBranchName(),taskCl->GetJetOutputBranch());
440        }
441        
442        taskCl = AddTaskJetCluster("AOD","",kHighPtFilterMask,iPhysicsSelectionFlag,"ANTIKT",0.4,0,1,kDeltaAODJetName.Data(),0.15);
443        taskCl->SetCentralityCut(fCenLo,fCenUp);
444        if(kDeltaAODJetName.Length()==0)taskCl->SetJetTriggerPtCut(40.);//
445        taskCl->SetBackgroundBranch(kDefaultJetBackgroundBranch.Data());
446        kDefaultJetBranch = taskCl->GetJetOutputBranch();
447
448
449        taskCl = AddTaskJetCluster("AOD","",kHighPtFilterMask,iPhysicsSelectionFlag,"ANTIKT",0.2,0,1,kDeltaAODJetName.Data(),0.15);
450        taskCl->SetCentralityCut(fCenLo,fCenUp);
451        taskCl->SetBackgroundBranch(kDefaultJetBackgroundBranch.Data());
452
453        if (!taskCl) ::Warning("AnalysisTrainPWG4", "AliAnalysisTaskCluster cannot run for this train conditions - EXCLUDED");
454      }
455    }
456
457    if (iDIJETAN) {
458       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskDiJets.C");
459       AliAnalysisTaskDiJets *taskdijets = 0;
460       if(iDIJETAN&1)taskdijets = AddTaskDiJets(); 
461       if (!taskdijets) ::Warning("AnalysisTrainPWG4", "AliAnalysisTaskJets cannot run for this train conditions - EXCLUDED");
462       if(iDIJETAN&2){
463         taskdijets = AddTaskDiJets("jetsAOD_CDF07"); 
464         taskdijets = AddTaskDiJets("jetsAOD_DA07"); 
465         taskdijets = AddTaskDiJets("jetsAOD_FASTJET07"); 
466         taskdijets = AddTaskDiJets("jetsAOD_FASTKT07"); 
467         taskdijets = AddTaskDiJets("jetsAOD_SISCONE07"); 
468         taskdijets = AddTaskDiJets("jetsAOD_UA107");
469       }
470    }
471
472    if(iPWG4JetServices){
473      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetServices.C");
474      AliAnalysisTaskJetServices *taskjetServ = 0;
475      taskjetServ = AddTaskJetServices();
476      if (!taskjetServ) ::Warning("AnalysisTrainPWG4", "AliAnalysisTaskJetServices cannot run for this train conditions - EXCLUDED");
477      if(kGridRunRange[0]>0)taskjetServ->SetRunRange(kGridRunRange[0],kGridRunRange[1]);
478      else taskjetServ->SetRunRange(110000,160000);
479      taskjetServ->SetMCData(kIsMC);
480      taskjetServ->SetUsePhysicsSelection((Bool_t)iPhysicsSelection);
481      taskjetServ->SetPhysicsSelectionFlag(iPhysicsSelectionFlag); // 
482      taskjetServ->SetDebugLevel(0);
483      taskjetServ->SetNonStdFile(kDeltaAODJetName.Data());
484      if(kIsPbPb){
485        taskjetServ->SetFilterAODCollisions(kTRUE);
486        taskjetServ->SetZVertexCut(8.);
487      }
488      if(iAODanalysis){
489        taskjetServ->SetAODInput(kTRUE);
490      }
491    }
492
493    if(iPWG4JetSpectrum){
494      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetSpectrum2.C");
495      AliAnalysisTaskJetSpectrum2 *taskjetSpectrum = 0;
496      if(iPWG4JetSpectrum&1){
497        taskjetSpectrum = AddTaskJetSpectrum2(kDefaultJetBranch.Data(),"",kDefaultJetBackgroundBranch.Data(),kHighPtFilterMask,AliVEvent::kMB,0,0);
498        if(kIsPbPb){
499          taskjetSpectrum = AddTaskJetSpectrum2(kDefaultJetBranch.Data(),"",kDefaultJetBackgroundBranch.Data(),kHighPtFilterMask,AliVEvent::kMB,0,1);
500          taskjetSpectrum = AddTaskJetSpectrum2(kDefaultJetBranch.Data(),"",kDefaultJetBackgroundBranch.Data(),kHighPtFilterMask,AliVEvent::kMB,0,2);
501          taskjetSpectrum = AddTaskJetSpectrum2(kDefaultJetBranch.Data(),"",kDefaultJetBackgroundBranch.Data(),kHighPtFilterMask,AliVEvent::kMB,0,3);
502          taskjetSpectrum = AddTaskJetSpectrum2(kDefaultJetBranch.Data(),"",kDefaultJetBackgroundBranch.Data(),kHighPtFilterMask,AliVEvent::kMB,0,4);
503        }
504      }
505      if (!taskjetSpectrum) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJetSpectrum2 cannot run for this train conditions - EXCLUDED");
506      
507    }
508
509
510    if(iPWG4Fragmentation){
511      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskFragmentationFunction.C");
512        AliAnalysisTaskFragmentationFunction *taskFrag = 0;
513      if(kUseAODMC){
514
515      }
516      else{
517        taskFrag = AddTaskFragmentationFunction(kDefaultJetBranch.Data(),"","","",kHighPtFilterMask);
518      }
519
520      if (!taskFrag) ::Warning("AnalysisTrainPWG4", "AliAnalysisTaskFragmentationFunction cannot run for this train conditions - EXCLUDED");
521    }
522
523
524    if(iPWG4JetChem){
525      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetChem.C");
526      AliAnalysisTask *taskChem = AddTaskJetChem(kHighPtFilterMask);
527      if (!taskChem) ::Warning("AnalysisTrainPWG4", "AliAnalysisTaskJetChem cannot run for this train conditions - EXCLUDED");
528    }
529
530
531
532
533    if(iPWG4JCORRAN){
534      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJCORRANTask.C");
535      AliJCORRANTask* corran = AddTaskJCORRAN(kDeltaAODJCORRANName.Data(),0);
536      if(!corran)::Warning("AnalysisTrainPWG4Jets", "AliJCORRANTask cannot run for this train conditions - EXCLUDED");
537      else{
538        if(kDeltaAODJCORRANName.Length()>0)mgr->RegisterExtraFile(kDeltaAODJCORRANName.Data()); 
539      }
540    }
541
542    if(iPWG4LeadingUE){
543      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskLeadingTrackUE.C");
544      AliAnalysisTaskLeadingTrackUE *taskLeadingUE = AddTaskLeadingTrackUE(kUseMC);
545      if (!taskLeadingUE) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTasLeadingTrackkUE cannot run for this train conditions - EXCLUDED");
546      //     taskLeadingUE->SetFilterBit(64);
547    }
548
549
550    if(iPWG4QGSep){
551      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskQGSep.C");
552      AliAnalysisTaskQGSep *taskQGSep = AddTaskQGSep(kUseMC,iAODanalysis);
553      if(!taskQGSep)::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskQGSep cannot run for this train conditions - EXCLUDED");
554    }
555   
556
557    if(iPWG4Minijet){
558      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskMinijet.C");
559      AliAnalysisTaskMinijet *taskMini = AddTaskMinijet(-1,"esd",kUseMC,kGridDataSet);
560      // if we ha highmult trigger add another task
561      if(!taskMini)::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskMinjet cannot run for this train conditions - EXCLUDED");
562    }
563
564
565    if(iPWG4PtQAMC){
566      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPWG4HighPtQAMC.C");
567      AliPWG4HighPtQAMC *taskQAMC = 0;
568      if(kUseMC){
569        if(iPWG4PtQAMC&1)taskQAMC = AddTaskPWG4HighPtQAMC(kGridDataSet.Data(),0);
570        if(iPWG4PtQAMC&1)taskQAMC = AddTaskPWG4HighPtQAMC(kGridDataSet.Data(),1);
571      }
572      if (!taskQAMC) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskQAMC cannot run for this train conditions - EXCLUDED");
573    }
574
575    if(iPWG4PtQATPC){
576      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPWG4HighPtQATPConly.C");
577      AliPWG4HighPtQATPConly *taskQATPC = 0;
578      if(iPWG4PtQATPC&1)taskQATPC = AddTaskPWG4HighPtQATPConly(kGridDataSet.Data(),1);
579      if(iPWG4PtQATPC&2)taskQATPC = AddTaskPWG4HighPtQATPConly(kGridDataSet.Data(),2);
580
581  if (!taskQATPC) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskQATPC cannot run for this train conditions - EXCLUDED");
582    }
583
584    if(iPWG4Cosmics){
585      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPWG4CosmicCandidates.C");
586
587      AliPWG4CosmicCandidates *taskPWG4CosmicCandidates = AddTaskPWG4CosmicCandidates(0);
588      taskPWG4CosmicCandidates = AddTaskPWG4CosmicCandidates(1);
589
590      if (!taskPWG4CosmicCandidates) ::Warning("AnalysisTrainPWG4Jets", "AddTaskPWG4CosmicCandidates cannot run for this train conditions - EXCLUDED");
591    }
592
593
594    if(iPWG4PtSpectra){
595      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPWG4HighPtSpectra.C");
596      AliPWG4HighPtSpectra *taskPtSpectra = AddTaskPWG4HighPtSpectra(kGridDataSet.Data());
597      if (!taskPtSpectra) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskPtSpectra cannot run for this train conditions - EXCLUDED");
598    }
599    if(iPWG4KMeans){
600      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskKMeans.C");
601      AliAnalysisTaskKMeans *taskKMeans = AddTaskKMeans();
602      if (!taskKMeans) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskKMenans cannot run for this train conditions - EXCLUDED");
603    }
604
605    if(iPWG4PartCorr){
606      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPartCorr.C");
607      AliAnalysisTaskParticleCorrelation *taskpartcorrPHOS = AddTaskPartCorr("AOD", "PHOS",kFALSE,kIsMC);
608      if (!taskpartcorrPHOS) ::Warning("AnalysisTrainNew", "AliAnalysisTaskParticleCorrelation PHOS cannot run for this train conditions - EXCLUDED");
609      AliAnalysisTaskParticleCorrelation *taskpartcorrEMCAL = AddTaskPartCorr("AOD", "EMCAL",kFALSE,kIsMC);
610      if (!taskpartcorrEMCAL) ::Warning("AnalysisTrainNew", "AliAnalysisTaskParticleCorrelation EMCAL cannot run for this train conditions - EXCLUDED");
611      if(kDeltaAODPartCorrName.Length()>0)mgr->RegisterExtraFile(kDeltaAODPartCorrName.Data());
612    } 
613
614    if(iPWG4CaloQA){
615      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/QA/AddTaskCalorimeterQA.C");
616      AliAnalysisTaskParticleCorrelation *taskcaloQA =  AddTaskCalorimeterQA("ESD",kFALSE,kIsMC,kCaloQAOutputFileName.Data());
617      if(!taskcaloQA)::Warning("AnalysisTrainNew", "AliAnalysisTaskParticleCorrelation QA cannot run - EXCLUDED");
618      //  if(kCaloQAOutputFileName.Length()>0)mgr->RegisterExtraFile(kCaloQAOutputFileName.Data());
619    } 
620
621    if(iPWG4JetCorr){
622      //     using namespace JetCorrelHD;
623      TString cdir = gSystem->WorkingDirectory();
624      gSystem->ChangeDirectory(gSystem->ExpandPathName("$ALICE_ROOT/PWG4/macros/"));
625      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetCorrel.C");
626      AliAnalysisTaskJetCorrel *taskjetcorr = AddTaskJetCorrel();
627      gSystem->ChangeDirectory(cdir);
628      if (!taskjetcorr) ::Warning("AnalysisTrainNew", "AliAnalysisTaskJetCorrel  cannot run for this train conditions - EXCLUDED");
629    } 
630
631    if(iPWG4Tagged){
632      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskTaggedPhotons.C");
633      AliAnalysisTaskTaggedPhotons * taskTagged = AddTaskTaggedPhotons(kFALSE); // EMCAL
634      taskTagged = AddTaskTaggedPhotons(kTRUE); // PHOS 
635      if (!taskTagged) ::Warning("AnalysisTrainNew", "AliAnalysisTaskTaggedPhotons  cannot run for this train conditions - EXCLUDED");     
636    }
637    if (iPWG4omega3pi) {
638      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskomega3pi.C");
639      AliAnalysisTaskOmegaPi0PiPi *taskomega3pi = AddTaskomega3pi();
640      if (!taskomega3pi) ::Warning("AnalysisTrainNew", "AliAnalysisTaskomega3pi cannot run\
641  for these train conditions - EXCLUDED");
642    }
643
644    // PWG4 gamma conversion analysis
645    if (iPWG4GammaConv) {
646       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskGammaConversion.C");
647       TString cdir = gSystem->WorkingDirectory();
648       gSystem->ChangeDirectory(gSystem->ExpandPathName("$ALICE_ROOT/PWG4/macros/"));
649       //      TString gcArguments = "-run-on-train -run-jet -run-chic -run-neutralmeson -run-cf";
650       //      TString gcArguments = "-run-on-train -run-jet -run-neutralmeson -run-cf -use-own-xyz";
651       //      TString gcArguments = "-run-on-train -run-jet -run-neutralmeson -run-cf -use-own-xyz";
652       TString gcArguments = "-run-on-train -run-jet -run-omega-meson -use-own-xyz -run-neutralmeson -no-aod";
653       //      TString kGCAnalysisCutSelectionId="9003562000100310";
654       //      TString kGCAnalysisCutSelectionId="9003562000100312";
655       //      gcArguments.Append(Form(" -set-cut-selection %s ",kGCAnalysisCutSelectionId.Data()));
656       if(!kIsMC)gcArguments += " -mc-off";
657       AliAnalysisTaskGammaConversion * taskGammaConversion = AddTaskGammaConversion(gcArguments,mgr->GetCommonInputContainer());
658       gSystem->ChangeDirectory(cdir);
659       taskGammaConversion->SelectCollisionCandidates();
660       if (!taskGammaConversion) ::Warning("AnalysisTrainNew", "AliAnalysisTaskGammaConversion cannot run for these train conditions - EXCLUDED");
661    }   
662
663    if (iPWG4CaloConv) {
664       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskCaloConv.C");
665       AliAnalysisTaskCaloConv * taskCaloConv = AddTaskCaloConv();
666       if (!taskCaloConv) ::Warning("AnalysisTrainNew", "AliAnalysisTaskCaloConv cannot run for these train conditions - EXCLUDED");
667    }   
668
669
670
671    //==========================================================================
672    // FOR THE REST OF THE TASKS THE MACRO AddTaskXXX() is not yet implemented/
673    // Run the analysis
674    //    
675    if (kPluginUse) {
676       AliAnalysisGrid *alienHandler = CreateAlienHandler(plugin_mode);
677       AliAnalysisManager::GetAnalysisManager()->SetGridHandler(alienHandler);
678    }
679    
680    if (mgr->InitAnalysis()) {
681      mgr->PrintStatus();
682      // if (kSaveTrain || strlen(config_file)) gSystem->ChangeDirectory(kTrainName);
683      if (!strcmp(plugin_mode,"submit")&&smode=="GRID"){
684        TString alien_workdir = gGrid->GetHomeDirectory();
685        if (iAODanalysis) alien_workdir += "analysisAOD";
686        else              alien_workdir += "analysisESD";
687        if(kGridDataSet.Length()>0)alien_workdir += Form("/%s",kGridDataSet.Data());
688        AliAnalysisAlien *gridhandler = (AliAnalysisAlien*)mgr->GetGridHandler();
689        printf("=== AnalysisTrainPWG4Jets:: Registering jdl in the work directory alien://%s/%s, should be done by the manager! ===\n",
690               alien_workdir.Data(),gridhandler->GetGridOutputDir());
691
692        TString dest;
693        dest = Form("%s/%s/%s.jdl",alien_workdir.Data(),gridhandler->GetGridOutputDir(),kTrainName.Data());
694        if(AliAnalysisAlien::FileExists(dest.Data())){
695          //      Printf("%s exist on grid removing...",dest.Data());
696          //      gGrid->Rm(dest.Data());
697        }
698        TFile::Cp(Form("file:%s.jdl",kTrainName.Data()),Form("alien://%s",dest.Data()));
699
700
701        TString dest;
702        dest = Form("%s/%s/%s_merge.jdl",alien_workdir.Data(),gridhandler->GetGridOutputDir(),kTrainName.Data());
703        if(AliAnalysisAlien::FileExists(dest.Data())){
704          //      Printf("%s exist on grid removing...",dest.Data());
705          //      gGrid->Rm(dest.Data());
706        }
707        TFile::Cp(Form("file:%s_merge.jdl",kTrainName.Data()),Form("alien://%s",dest.Data()));
708
709        
710        dest = Form("%s/rootfiles/STEER/LQ1dRef_v1.root",gGrid->GetHomeDirectory());
711        if(AliAnalysisAlien::FileExists(dest.Data())){
712          Printf("%s exist on grid removing...",dest.Data());
713          gGrid->Rm(dest.Data());
714        }
715        TFile::Cp(Form("file:%s/STEER/LQ1dRef_v1.root",
716                       gSystem->ExpandPathName("$ALICE_ROOT")),Form("alien://%s",dest.Data()));
717      }
718      AliLog::SetGlobalLogLevel(AliLog::kError);
719      if((kUseSysInfo>0&&smode=="LOCAL")||!strcmp(plugin_mode, "test")){
720        TFile * fM = TFile::Open("manager_local.root","RECREATE");
721        mgr->Write();
722        fM->Close();
723      }
724      
725      // grmpf, aliroot error handler overwrites root
726      gErrorIgnoreLevel = kErrorIgnoreLevel;
727      if(gErrorIgnoreLevel>3000) AliLog::SetGlobalLogLevel(AliLog::kFatal);
728      StartAnalysis(smode, chain);
729      if((kUseSysInfo>0&&smode=="LOCAL")||!strcmp(plugin_mode, "test")){
730        for(int i = 0;i < mgr->GetTopTasks()->GetEntries();i++){
731          mgr->ProfileTask(i);
732        }
733      }
734      if (kSaveTrain && smode=="GRID") {
735        AliAnalysisAlien *gridhandler = (AliAnalysisAlien*)mgr->GetGridHandler();
736        TString alien_workdir = gGrid->GetHomeDirectory();
737        if (iAODanalysis) alien_workdir += "analysisAOD";
738        else              alien_workdir += "analysisESD";
739        if(kGridDataSet.Length()>0)alien_workdir += Form("/%s",kGridDataSet.Data());
740        //     kGridOutdir = gridhandler->GetGridOutputDir();
741        printf("=== Registering ConfigTrain.C in the work directory <%s> ===\n",
742                 alien_workdir.Data());
743        if (AliAnalysisAlien::FileExists(Form("%s/%sConfig.C", alien_workdir.Data(), kTrainName.Data())))
744          gGrid->Rm(Form("%s/%sConfig.C", alien_workdir.Data(), kTrainName.Data()));
745        if (strcmp(plugin_mode, "test"))
746          TFile::Cp(Form("file:%sConfig.C",kTrainName.Data()), Form("alien://%s/%sConfig.C", alien_workdir.Data(), kTrainName.Data()));
747      }
748    }
749 }
750
751 //______________________________________________________________________________
752 void StartAnalysis(const char *mode, TChain *chain) {
753 // Start analysis.
754    Int_t imode = -1;
755    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
756    if (!strcmp(mode, "LOCAL")) imode = 0;
757    if (!strcmp(mode, "PROOF")) imode = 1;
758    if (!strcmp(mode, "GRID"))  imode = 2;
759    switch (imode) {
760       case 0:
761          if (!chain) {
762             ::Error("AnalysisTrainPWG4Jets.C::StartAnalysis", "Cannot create the chain");
763             return;
764          }   
765          mgr->StartAnalysis(mode, chain,kNumberOfEvents);
766          return;
767       case 1:
768          if (!kProofDataSet.Length()) {
769             ::Error("AnalysisTrainPWG4Jets.C::StartAnalysis", "kProofDataSet is empty");
770             return;
771          }   
772          mgr->StartAnalysis(mode, kProofDataSet, kProofEvents,kProofOffset);
773          return;
774       case 2:
775          if (kPluginUse) {
776             if (!mgr->GetGridHandler()) {
777                ::Error("AnalysisTrainPWG4Jets.C::StartAnalysis", "Grid plugin not initialized");
778                return;
779             }   
780             mgr->StartAnalysis("grid",chain,kNumberOfEvents);
781          } else {
782             if (!chain) {
783                ::Error("AnalysisTrainPWG4Jets.C::StartAnalysis", "Cannot create the chain");
784                return;
785             }   
786             mgr->StartAnalysis(mode, chain);
787             mgr->StartAnalysis(mode, chain,kNumberOfEvents);
788          }   
789          return;
790    }      
791 }          
792     
793 //______________________________________________________________________________
794 void CheckModuleFlags(const char *mode) {
795 // Checks selected modules and insure compatibility
796    Int_t imode = -1;
797    if (!strcmp(mode, "LOCAL")) imode = 0;
798    if (!strcmp(mode, "PROOF")) imode = 1;
799    if (!strcmp(mode, "GRID"))  imode = 2;
800
801
802    if (kUseCPAR) {
803      kPluginAliRootVersion    = ""; // NO aliroot if we use CPAR
804    }
805
806    if (imode==1) {
807       if (!kUsePAR) {
808          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PAR files enabled due to PROOF analysis");
809          kUsePAR = kTRUE;
810       }   
811    }  
812    if (imode != 2) {
813       ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "AliEn plugin disabled since not in GRID mode");
814       kPluginUse = kFALSE; 
815    }   
816
817
818    if(!kIsMC){
819      // switch off anthin related to MC
820      kUseMC = 0;
821      kUseAODMC = 0;
822      kUseTR = kFALSE;
823    }
824
825    // Decide if we have PbPb
826    if(kGridDataSet.CompareTo("LHC10h")==0||kGridDataSet.Contains("LHC10h")) {
827      Printf("Using settings for Pb+Pb");
828      kIsPbPb = true;
829    }
830
831    
832
833    if (iAODanalysis) {
834    // AOD analysis
835       if (kUseMC)
836          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "MC usage disabled in analysis on AOD's");
837       if (kUseAODTags)
838          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "AOD tags usage disabled in analysis on AOD's");
839       kUseMC = kFALSE;
840       kUseTR = kFALSE;
841       kUseAODTags = kFALSE;
842       if (iESDfilter)
843          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "ESD filter disabled in analysis on AOD's");
844       iESDfilter   = 0;
845       if (iPhysicsSelection)
846          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "Physics Selection disabled in analysis on AOD's");
847       iPhysicsSelection   = 0;
848       if (!iAODhandler) {
849          if (iJETAN) 
850             ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "JETAN disabled in analysis on AOD's without AOD handler");
851          iJETAN = 0;
852          iDIJETAN = 0;
853       }
854       // Disable tasks that do not work yet on AOD data
855       if(iPWG4JCORRAN)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 JCORRAN disabled in analysis on AOD's");
856       iPWG4JCORRAN = 0;
857       if( iPWG4PtQAMC)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 PtQAMC disabled in analysis on AOD's");
858       iPWG4PtQAMC        = 0;
859       if( iPWG4PtQATPC)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 PtTPC disabled in analysis on AOD's");
860       iPWG4PtQATPC        = 0;
861       if( iPWG4Cosmics)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 Comics disabled in analysis on AOD's");
862       iPWG4Cosmics        = 0;
863
864       if( iPWG4PtSpectra)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 PtQAMC disabled in analysis on AOD's");
865       iPWG4PtSpectra     = 0;
866       if(iPWG4KMeans)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4KMeans disabled on AOD's");
867       iPWG4KMeans       = 0;
868       if (iPWG4JetCorr)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4Jetcorr disabled on AOD's");
869       iPWG4JetCorr = 0;
870       if (iPWG4PartCorr)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4partcorr disabled on AOD's");
871       iPWG4PartCorr = 0;
872       if (iPWG4CaloQA)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4CaloQA disabled on AOD's");
873       iPWG4CaloQA = 0;
874       if (iPWG4Tagged)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4tagged disabled on AOD's");
875       iPWG4Tagged = 0;
876       if (iPWG4omega3pi)
877         ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG4omega3pi disabled on AOD's");
878       iPWG4omega3pi = 0;
879       if (iPWG4GammaConv)::Info("AnalysisPWG4Jets.C::CheckModuleFlags", "PWG4gammaconv disabled on AOD's");
880       iPWG4GammaConv = 0;   
881       iCentralitySelection = 0;
882    } else {   
883    // ESD analysis
884
885      if(kIsPbPb){
886        iCentralitySelection = 1;
887      }
888
889      if (!kUseMC){
890        kUseTR = kFALSE;
891        
892        if(kUseKinefilter)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 Kine Filter disabled in analysis without MC");
893        kUseKinefilter = kFALSE;
894        if( iPWG4PtQAMC)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 PtQAMC disabled in analysis without MC");
895        iPWG4PtQAMC        = 0;
896      }
897      if (!kUseTR) {
898        if(iPWG4PtQAMC)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "iPWG4QATPCMC disabled if not reading track references");
899        iPWG4PtQAMC        = 0;
900      }   
901      if (iJETAN){
902        iESDfilter=1;
903      }
904       if (!iESDfilter){
905         kUseKinefilter = kFALSE;
906         kUseMuonfilter = kFALSE;
907       }
908       if(!iJETAN){
909         iPWG4JetSpectrum = iPWG4QGSep = iDIJETAN = 0;
910       }
911    }
912    iPWG4JetTasks = iPWG4JetServices||iPWG4JetSpectrum||iPWG4LeadingUE||iPWG4PtQAMC||iPWG4PtSpectra||iPWG4PtQATPC||iPWG4Cosmics||iPWG4QGSep||iPWG4JetChem||iPWG4Minijet||iPWG4Fragmentation;
913    iPWG4PartCorrLibs = iPWG4PartCorr||iPWG4Tagged||iPWG4CaloQA;
914    iPWG4GammaConvLib = iPWG4GammaConv||iPWG4CaloConv;
915
916
917    iEMCUtilLibs = iPWG4PartCorrLibs||iPWG4JCORRAN||iPWG4GammaConvLib;
918    iJETANLib = iPWG4JetTasks||iJETAN||iDIJETAN;
919
920    if (iESDfilter) {iAODhandler=1;}
921    if (kUseKinefilter && !kUseMC) kUseKinefilter = kFALSE;
922    if (kUseAODTags && !iAODhandler) kUseAODTags = kFALSE;
923
924
925    
926 }
927
928 //______________________________________________________________________________
929 Bool_t Connect(const char *mode) {
930 // Connect <username> to the back-end system.
931    Int_t imode = -1;
932    if (!strcmp(mode, "LOCAL")) imode = 0;
933    if (!strcmp(mode, "PROOF")) imode = 1;
934    if (!strcmp(mode, "GRID"))  imode = 2;
935    TString username = gSystem->Getenv("alien_API_USER");
936    switch (imode) {
937       case 0:
938          break;
939       case 1:
940          if  (!username.Length()) {
941             ::Error(Form("AnalysisTrainPWG4Jets.C::Connect <%s>", mode), "Make sure you:\n \
942                            1. Have called: alien-token-init <username>\n \
943                            2. Have called: >source /tmp/gclient_env_$UID");
944             return kFALSE;
945          }
946          ::Info("AnalysisTrainPWG4Jets.C::Connect", "Connecting user <%s> to PROOF cluster <%s>", 
947                 username.Data(), kProofCluster.Data());
948          gEnv->SetValue("XSec.GSI.DelegProxy", "2");
949 //         TProof::Open(Form("%s@%s:31093", username.Data(), kProofCluster.Data()));       
950          TProof::Open(Form("%s@%s", username.Data(), kProofCluster.Data()));       
951          if (!gProof) {
952             if (strcmp(gSystem->Getenv("XrdSecGSISRVNAMES"), "lxfsrd0506.cern.ch"))
953                ::Error(Form("AnalysisTrainPWG4Jets.C::Connect <%s>", mode), "Environment XrdSecGSISRVNAMES different from lxfsrd0506.cern.ch");
954             return kFALSE;
955          }
956          if(kProofClearPackages)gProof->ClearPackages();
957
958          if(kProofSaveToAlien){
959            TGrid::Connect("alien://");
960            if (gGrid) {
961              TString homedir = gGrid->GetHomeDirectory();
962              TString workdir = homedir + kTrainName;
963              if (!gGrid->Cd(workdir)) {
964                gGrid->Cd(homedir);
965                if (gGrid->Mkdir(workdir)) {
966                  gGrid->Cd(kTrainName);
967                  ::Info("AnalysisTrainPWG4Jets::Connect()", "Directory %s created", gGrid->Pwd());
968                }
969              }
970              gGrid->Mkdir("proof_output");
971              gGrid->Cd("proof_output");
972              kProofOutdir = Form("alien://%s", gGrid->Pwd());
973            }   
974          }
975          break;
976       case 2:      
977          if  (!username.Length()) {
978             ::Error(Form("AnalysisTrainPWG4Jets.C::Connect <%s>", mode), "Make sure you:\n \
979                            1. Have called: alien-token-init <username>\n \
980                            2. Have called: >source /tmp/gclient_env_$UID");
981             return kFALSE;
982          }
983          if (kPluginUse && !gSystem->Getenv("alien_CLOSE_SE")) {
984             ::Error(Form("AnalysisTrainPWG4Jets.C::Connect <%s>", mode), 
985                            "When using the AliEn plugin it is preferable to define the \
986                            variable alien_CLOSE_SE in your environment.");
987             return kFALSE;
988          }
989          ::Info("AnalysisTrainPWG4Jets.C::Connect", "Connecting user <%s> to AliEn ...", 
990                 username.Data());
991          TGrid::Connect("alien://");
992          if (!gGrid || !gGrid->IsConnected()) return kFALSE;
993          break;
994       default:
995          ::Error("AnalysisTrainPWG4Jets.C::Connect", "Unknown run mode: %s", mode);
996          return kFALSE;
997    }
998    ::Info("AnalysisTrainPWG4Jets.C::Connect","Connected in %s mode", mode);
999    return kTRUE;
1000 }
1001
1002 //______________________________________________________________________________
1003 Bool_t LoadCommonLibraries(const char *mode)
1004 {
1005 // Load common analysis libraries.
1006    Int_t imode = -1;
1007    if (!strcmp(mode, "LOCAL")) imode = 0;
1008    if (!strcmp(mode, "PROOF")) imode = 1;
1009    if (!strcmp(mode, "GRID"))  imode = 2;
1010    if (!gSystem->Getenv("ALICE_ROOT")) {
1011       ::Error("AnalysisTrainPWG4Jets.C::LoadCommonLibraries", "Analysis train requires that ALICE_ROOT is set to pick up Configurations"); 
1012       return kFALSE;
1013    }   
1014    Bool_t success = kTRUE;
1015    // ROOT libraries
1016    gSystem->Load("libTree.so");
1017    gSystem->Load("libGeom.so");
1018    gSystem->Load("libVMC.so");
1019    gSystem->Load("libPhysics.so");
1020    
1021    // Load framework classes. Par option ignored here.
1022    switch (imode) {
1023       case 0:
1024       case 2:
1025          if (kUseCPAR) {
1026             success &= LoadLibrary("STEERBase", mode, kTRUE);
1027             success &= LoadLibrary("ESD", mode, kTRUE);
1028             success &= LoadLibrary("AOD", mode, kTRUE);
1029             success &= LoadLibrary("ANALYSIS", mode, kTRUE);
1030             success &= LoadLibrary("ANALYSISalice", mode, kTRUE);
1031             success &= LoadLibrary("EventMixing", mode,kTRUE);
1032             success &= LoadLibrary("CORRFW", mode, kTRUE);
1033          } else {   
1034             success &= LoadLibrary("libSTEERBase.so", mode);
1035             success &= LoadLibrary("libESD.so", mode);
1036             success &= LoadLibrary("libAOD.so", mode);
1037             success &= LoadLibrary("libANALYSIS.so", mode);
1038             success &= LoadLibrary("libANALYSISalice.so", mode);
1039             success &= LoadLibrary("libEventMixing.so", mode);
1040             success &= LoadLibrary("libCORRFW.so", mode);
1041             gROOT->ProcessLine(".include $ALICE_ROOT/include");
1042          }   
1043          break;
1044       case 1:
1045          Int_t ires = -1;
1046          if (kProofUseAFPAR && !gSystem->AccessPathName(kProofAFversion)) ires = gProof->UploadPackage(kProofAFversion);
1047          if (ires < 0) {
1048             success &= LoadLibrary("STEERBase", mode);
1049             success &= LoadLibrary("ESD", mode);
1050             success &= LoadLibrary("AOD", mode);
1051             success &= LoadLibrary("ANALYSIS", mode);
1052             success &= LoadLibrary("ANALYSISalice", mode);
1053             success &= LoadLibrary("EventMixing", mode);
1054             success &= LoadLibrary("CORRFW", mode);
1055          } else { 
1056             ires = gProof->EnablePackage(kProofAFversion);
1057             if (ires<0) success = kFALSE;
1058             success &= LoadLibrary("CORRFW", mode);
1059          }
1060          break;         
1061       default:
1062          ::Error("AnalysisTrainPWG4Jets.C::LoadCommonLibraries", "Unknown run mode: %s", mode);
1063          return kFALSE;
1064    }
1065    if (success) {
1066       ::Info("AnalysisTrainPWG4Jets.C::LoadCommodLibraries", "Load common libraries:    SUCCESS");
1067       ::Info("AnalysisTrainPWG4Jets.C::LoadCommodLibraries", "Include path for Aclic compilation:\n%s",
1068               gSystem->GetIncludePath());
1069    } else {           
1070       ::Info("AnalysisTrainPWG4Jets.C::LoadCommodLibraries", "Load common libraries:    FAILED");
1071    }   
1072       
1073    return success;
1074 }
1075
1076 //______________________________________________________________________________
1077 Bool_t LoadAnalysisLibraries(const char *mode)
1078 {
1079 // Load common analysis libraries.
1080   Bool_t success = kTRUE;
1081   if (useTender) {
1082       if (!LoadLibrary("TENDER", mode, kTRUE) ||
1083           !LoadLibrary("TENDERSupplies", mode, kTRUE)) return kFALSE;
1084    }
1085    if (iESDfilter) {
1086      /*
1087       if (!LoadLibrary("PWG3base", mode, kTRUE) ||
1088           !LoadLibrary("PWG3muon", mode, kTRUE)) return kFALSE;
1089      */
1090    }   
1091    // JETAN
1092    if (iJETANLib) {
1093      // this part needs some rework in case we do not need the fastjed finders for processing
1094      if (!LoadLibrary("JETAN", mode, kTRUE)) return kFALSE;
1095      if (!strcmp(mode, "PROOF")){
1096        gProof->Exec("gSystem->Load\(\"/afs/cern.ch/user/d/dperrino/public/libCGAL.so\"\)", kTRUE); 
1097        gProof->Exec("gSystem->Load\(\"/afs/cern.ch/user/d/dperrino/public/libfastjet.so\"\)", kTRUE); 
1098        // problem when loading siscone copiled with different gcc version??
1099        // gProof->Exec("gSystem->Load\(\"/afs/cern.ch/user/d/dperrino/public/libsiscone.so\"\)", kTRUE); 
1100        gProof->Exec("gSystem->Load\(\"/afs/cern.ch/user/d/dperrino/public/libSISConePlugin.so\"\)", kTRUE);      
1101      }
1102      if(!kUsePAR){ 
1103        if (!LoadLibrary("CGAL", mode, kTRUE)) return kFALSE;
1104        if (!LoadLibrary("fastjet", mode, kTRUE)) return kFALSE;
1105        if (!LoadLibrary("siscone", mode, kTRUE)) return kFALSE;
1106        if (!LoadLibrary("SISConePlugin", mode, kTRUE)) return kFALSE;
1107      }
1108      else{
1109        // par files plus FASTJET needs some extra work... need to change
1110        // the loading sequence in the auto generated .C file
1111        if (!LoadLibrary("libCGAL.so", mode, kTRUE)) return kFALSE;
1112        if (!LoadLibrary("libfastjet.so", mode, kTRUE)) return kFALSE;
1113        if (!LoadLibrary("libsiscone.so", mode, kTRUE)) return kFALSE;
1114        if (!LoadLibrary("libSISConePlugin.so", mode, kTRUE)) return kFALSE;
1115      }
1116      if (!LoadLibrary("FASTJETAN", mode, kTRUE)) return kFALSE;
1117    }
1118    if(iPWG4JetTasks){
1119      if (!LoadLibrary("PWG4JetTasks", mode, kTRUE)) return kFALSE;
1120    }
1121
1122    if(iEMCUtilLibs){
1123      if (!LoadLibrary("EMCALUtils", mode, kTRUE) ||
1124          !LoadLibrary("PHOSUtils", mode, kTRUE)) return kFALSE;
1125    }
1126
1127    if (iPWG4PartCorrLibs) {   
1128       if (!LoadLibrary("PWG4PartCorrBase", mode, kTRUE) ||
1129           !LoadLibrary("PWG4PartCorrDep", mode, kTRUE)) return kFALSE;
1130    }
1131    if(iPWG4JCORRAN){
1132      // PWG4 particle correlations
1133      if(!LoadLibrary("PWG4JCORRAN",mode,kTRUE))return kFALSE;
1134    }
1135    if (iPWG4JetCorr) { 
1136      if (!LoadLibrary("PWG4JetCorrel", mode, kTRUE)) return kFALSE;
1137    }  
1138    if (iPWG4omega3pi) {
1139      if (!LoadLibrary("PWG4omega3pi", mode, kTRUE)) return kFALSE;
1140    }
1141    if (iPWG4GammaConvLib) {
1142       if (!LoadLibrary("PWG4GammaConv", mode, kTRUE)) return kFALSE;
1143    }      
1144
1145    ::Info("AnalysisTrainPWG4Jets.C::LoadAnalysisLibraries", "Load other libraries:   SUCCESS");
1146    return kTRUE;
1147 }
1148
1149 //______________________________________________________________________________
1150 Bool_t LoadLibrary(const char *module, const char *mode, Bool_t rec=kFALSE)
1151 {
1152 // Load a module library in a given mode. Reports success.
1153    Int_t imode = -1;
1154    Int_t result;
1155    TString smodule(module);
1156    if (!strcmp(mode, "LOCAL")) imode = 0;
1157    if (!strcmp(mode, "PROOF")) imode = 1;
1158    if (!strcmp(mode, "GRID"))  imode = 2;
1159    TString mod(module);
1160    if (!mod.Length()) {
1161       ::Error("AnalysisTrainPWG4Jets.C::LoadLibrary", "Empty module name");
1162       return kFALSE;
1163    }   
1164    // If a library is specified, just load it
1165    if (smodule.EndsWith(".so")) {
1166       mod.Remove(mod.Index(".so"));
1167       result = gSystem->Load(mod);
1168       if (result < 0) {
1169          ::Error("AnalysisTrainPWG4Jets.C::LoadLibrary", "Could not load library %s", module);
1170          return kFALSE;
1171       }
1172       if (rec) anaLibs += Form("%s.so ",mod.Data()); 
1173       if (rec) anaLibsExtra += Form("%s.so ",mod.Data()); 
1174       return kTRUE;
1175    } 
1176    // Check if the library is already loaded
1177    if (strlen(gSystem->GetLibraries(Form("%s.so", module), "", kFALSE)) > 0)
1178       return kTRUE;    
1179    switch (imode) {
1180       case 0:
1181       case 2:
1182          if (kUsePAR) {
1183             result = SetupPar(module);
1184             if (rec) anaPars += Form("%s.par ", module);
1185          } else {
1186             result = gSystem->Load(Form("lib%s.so", module));
1187             if (rec) anaLibs += Form("lib%s.so ", module);
1188          }   
1189          break;
1190       case 1:
1191         if(!gSystem->AccessPathName(module)){
1192           ::Info("AnalysisTrainPWG4Jets.C::LoadLibrary", "Removing directory %s",module);
1193           gSystem->Exec(Form("rm -rf %s",module));
1194         }
1195          result = gProof->UploadPackage(module);
1196          if (result<0) {
1197             result = gProof->UploadPackage(gSystem->ExpandPathName(Form("$ALICE_ROOT/%s.par", module)));
1198             if (result<0) {
1199                ::Error("AnalysisTrainPWG4Jets.C::LoadLibrary", "Could not find module %s.par in current directory nor in $ALICE_ROOT", module);
1200                return kFALSE;
1201             }
1202          }   
1203          result = gProof->EnablePackage(module);
1204          break;
1205       default:
1206          return kFALSE;
1207    }         
1208    if (result < 0) {
1209       ::Error("AnalysisTrainPWG4Jets.C::LoadLibrary", "Could not load module %s", module);
1210       return kFALSE;
1211    }
1212    return kTRUE;
1213 }           
1214
1215
1216
1217 //______________________________________________________________________________
1218 Bool_t LoadSource(const char *source, const char *mode, Bool_t rec=kFALSE)
1219 {
1220 // Load a module library in a given mode. Reports success.
1221    Int_t imode = -1;
1222    Int_t result = -1;
1223    if (!strcmp(mode, "LOCAL")) imode = 0;
1224    if (!strcmp(mode, "PROOF")) imode = 1;
1225    if (!strcmp(mode, "GRID"))  imode = 2;
1226    TString ssource(source);
1227    TString basename = gSystem->BaseName(ssource.Data());
1228    if (!ssource.Length()) {
1229       ::Error("AnalysisTrainPWG4Jets.C::LoadSource", "Empty task name");
1230       return kFALSE;
1231    }   
1232    // we have a source code so compile it
1233    if (ssource.EndsWith(".cxx")) {
1234      // need to copy it here other wise the path is also used on grid...
1235      ssource.Remove(ssource.Index(".cxx"));
1236      basename.Remove(basename.Index(".cxx"));
1237      Printf("LoadSources:: Copying...  path %s{cxx,h}",ssource.Data());
1238      gSystem->Exec(Form("cp %s.cxx . ",ssource.Data()));
1239      gSystem->Exec(Form("cp %s.h . ",ssource.Data()));
1240      // Path to code
1241      // only needed for local compilation, in grid and proof mode 
1242      // the task headers are uploaded 
1243      //     path.Remove(path.Index(gSystem->BaseName(path.Data())));
1244      // Printf("LoadSources:: Including path %s",path.Data());
1245      //  if(path.Length()>0)gROOT->ProcessLine(Form(".include %s",path.Data()));
1246      Printf("LoadSources:: Loading...  path %s",basename.Data());
1247      switch (imode) {
1248      case 0:
1249        result = gROOT->LoadMacro(Form("%s.cxx++g",basename.Data()));
1250        break;
1251      case 1:
1252        result = gProof->LoadMacro(Form("%s.cxx++g",basename.Data()));
1253        break;
1254      case 2:
1255        result = gROOT->LoadMacro(Form("%s.cxx++g",basename.Data()));
1256        if (rec){
1257          // what we want to compile
1258          anaSources += Form("%s.cxx ",basename.Data()); 
1259          // what we need as input...
1260          anaLibs += Form("%s.cxx %s.h ",basename.Data(),basename.Data()); 
1261        }
1262        break;
1263      default:
1264        return kFALSE;
1265      }
1266    } 
1267    if (result < 0) {
1268       ::Error("AnalysisTrainPWG4Jets.C::LoadSources", "Could not load source %s", source);
1269       return kFALSE;
1270    }
1271    return kTRUE;
1272 }           
1273
1274
1275 //______________________________________________________________________________
1276 TChain *CreateChain(const char *mode, const char *plugin_mode)
1277 {
1278 // Create the input chain
1279    Int_t imode = -1;
1280    if (!strcmp(mode, "LOCAL")) imode = 0;
1281    if (!strcmp(mode, "PROOF")) imode = 1;
1282    if (!strcmp(mode, "GRID"))  imode = 2;
1283    TChain *chain = NULL;
1284    // Local chain
1285    switch (imode) {
1286       case 0:
1287          if (iAODanalysis) {
1288             if (!kLocalXMLDataset.Length()) {
1289                // Local AOD
1290                chain = new TChain("aodTree");
1291                TString line;
1292                ifstream in;
1293                in.open(kLocalDataList.Data());
1294                while (in.good()) {
1295                  in >> line;
1296                  if (line.Length() == 0) continue;
1297                  // cout << " line = " << line << endl;
1298                  chain->Add(line.Data());
1299                }       
1300             } else {
1301                // Interactive AOD
1302                chain = CreateChainSingle(kLocalXMLDataset, "aodTree");
1303             }
1304          } else {      
1305            if (!kLocalXMLDataset.Length()) {
1306              // Local ESD
1307              chain = new TChain("esdTree");
1308              TString line;
1309              ifstream in;
1310              in.open(kLocalDataList.Data());
1311              while (in.good()) {
1312                in >> line;
1313                if (line.Length() == 0) continue;
1314                cout << " line = " << line << endl;
1315                chain->Add(line.Data());
1316              }       
1317            } else {
1318              // Interactive ESD
1319                chain = CreateChainSingle(kLocalXMLDataset, "esdTree");
1320            }   
1321          }
1322          break;
1323       case 1:
1324          break;
1325       case 2:
1326          if (kPluginUse) {
1327 //            AliAnalysisGrid *alienHandler = CreateAlienHandler(plugin_mode);
1328 //            AliAnalysisManager::GetAnalysisManager()->SetGridHandler(alienHandler);
1329          } else {
1330             TString           treeName = "esdTree";
1331             if (iAODanalysis) treeName = "aodTree";
1332             chain = CreateChainSingle("wn.xml", treeName);
1333          }
1334          break;      
1335       default:   
1336    }
1337    if (chain && chain->GetNtrees()) return chain;
1338    return NULL;
1339 }   
1340
1341 //______________________________________________________________________________
1342 TChain* CreateChainSingle(const char* xmlfile, const char *treeName)
1343 {
1344    printf("*******************************\n");
1345    printf("*** Getting the ESD Chain   ***\n");
1346    printf("*******************************\n");
1347    TAlienCollection * myCollection  = TAlienCollection::Open(xmlfile);
1348
1349    if (!myCollection) {
1350       ::Error("AnalysisTrainPWG4Jets.C::CreateChainSingle", "Cannot create an AliEn collection from %s", xmlfile) ;
1351       return NULL ;
1352    }
1353
1354    TChain* chain = new TChain(treeName);
1355    myCollection->Reset() ;
1356    while ( myCollection->Next() ) chain->Add(myCollection->GetTURL("")) ;
1357    chain->ls();
1358    return chain;
1359 }
1360
1361 //______________________________________________________________________________
1362 Int_t SetupPar(char* pararchivename)
1363 {
1364    if (!pararchivename || !strlen(pararchivename)) return -1;
1365    char processline[1024];
1366    if (gSystem->AccessPathName(Form("%s.par", pararchivename))) {
1367       if (!gSystem->AccessPathName(Form("%s/%s.par", gSystem->Getenv("ALICE_ROOT"),pararchivename))) {
1368          ::Info("AnalysisTrainPWG4Jets.C::SetupPar", "Getting %s.par from $ALICE_ROOT", pararchivename);
1369         TFile::Cp(gSystem->ExpandPathName(Form("$ALICE_ROOT/%s.par", pararchivename)), 
1370                   Form("%s.par",pararchivename));
1371       } else {
1372          ::Error("AnalysisTrainPWG4Jets.C::SetupPar", "Cannot find %s.par", pararchivename);
1373          return -1;
1374       }   
1375    }
1376    if (kPluginUse && kSaveTrain) gSystem->Exec(Form("ln -s ../%s.par %s",pararchivename, kTrainName.Data()));
1377    gSystem->Exec(Form("tar xvzf %s.par", pararchivename));
1378
1379    TString ocwd = gSystem->WorkingDirectory();
1380    if (!gSystem->ChangeDirectory(pararchivename)) return -1;
1381         
1382    // check for BUILD.sh and execute
1383    if (!gSystem->AccessPathName("PROOF-INF/BUILD.sh")) {
1384       printf("*******************************\n");
1385       printf("*** Building PAR archive    ***\n");
1386       printf("*******************************\n");          
1387       if (gSystem->Exec("PROOF-INF/BUILD.sh")) {
1388          Error("runProcess","Cannot Build the PAR Archive! - Abort!");
1389          return -1;
1390       }
1391    }
1392
1393         // check for SETUP.C and execute
1394         if (!gSystem->AccessPathName("PROOF-INF/SETUP.C")) {
1395             printf("*******************************\n");
1396             printf("*** Setup PAR archive       ***\n");
1397             printf("*******************************\n");
1398             gROOT->Macro("PROOF-INF/SETUP.C");
1399         }       
1400         if (!gSystem->ChangeDirectory(ocwd.Data())) return -1;
1401    return 0;
1402 }
1403
1404 //______________________________________________________________________________
1405 AliAnalysisAlien* CreateAlienHandler(const char *plugin_mode)
1406 {
1407 // Check if user has a valid token, otherwise make one. This has limitations.
1408 // One can always follow the standard procedure of calling alien-token-init then
1409 //   source /tmp/gclient_env_$UID in the current shell.
1410 //   if (!AliAnalysisGrid::CreateToken()) return NULL;
1411    AliAnalysisAlien *plugin = new AliAnalysisAlien();
1412 // Set the run mode (can be "full", "test", "offline", "submit" or "terminate")
1413    plugin->SetRunMode(plugin_mode);
1414    if (kPluginUseProductionMode) plugin->SetProductionMode();
1415    plugin->SetJobTag(kJobTag);
1416    plugin->SetNtestFiles(2);
1417 //   plugin->SetPreferedSE("ALICE::NIHAM::File");
1418 // Set versions of used packages
1419    plugin->SetAPIVersion("V1.1x");
1420    //   plugin->SetAPIVersion("V1.0x");
1421 //   plugin->SetAPIVersion("V2.4");
1422    plugin->SetROOTVersion(kPluginRootVersion);
1423    plugin->SetAliROOTVersion(kPluginAliRootVersion);
1424 // Declare input data to be processed.
1425 // Method 1: Create automatically XML collections using alien 'find' command.
1426 // Define production directory LFN
1427    plugin->SetGridDataDir(kGridDataDir.Data());
1428 // Set data search pattern
1429    if (iAODanalysis) plugin->SetDataPattern(" *AliAOD.root");
1430    //   else              plugin->SetDataPattern(Form(" %s/*/*ESD.tag.root",kGridPassPattern.Data()));
1431    else {
1432        plugin->SetDataPattern(Form(" %s/*/*AliESDs.root",kGridPassPattern.Data()));
1433    }
1434 // ...then add run numbers to be considered
1435    plugin->SetRunRange(kGridRunRange[0], kGridRunRange[1]);
1436    plugin->SetRunPrefix("000");
1437    /*
1438    for (Int_t i=kGridRunRange[0]; i<=kGridRunRange[1]; i++) {
1439      Printf("AnalysisTrainPWG4Jets Adding run number %s", Form(kGridRunPattern.Data(),i));
1440      plugin->AddRunNumber(Form(kGridRunPattern.Data(),i));
1441    }   
1442    */
1443
1444    if(kGridLocalRunList.Length()>0){
1445      ifstream in1;
1446      in1.open(kGridLocalRunList.Data());
1447      int iRun;
1448      int icount = 0;
1449      /*
1450      char c;
1451      char cLine[250];
1452      while(!in1.eof()){
1453        c = in1.get();
1454        if ( (c >= '0') && (c <= '9') )
1455          {
1456            in1.putback (c);
1457            in1>>iRun;
1458            Printf("AnalysisTrainPWG4Jets Adding run number from File %s", Form(kGridRunPattern.Data(),iRun));
1459            plugin->AddRunNumber(Form(kGridRunPattern.Data(),iRun));
1460        }
1461      else
1462        {
1463          in1.putback (c);
1464          in1.getline(cLine,250);
1465
1466        }
1467      }
1468      */
1469      
1470      Int_t nRun = 0;
1471
1472      // just use run numbers, negatives will be excluded
1473      while(in1>>iRun){
1474        if(iRun>=0){
1475          if(iRun>=0&&nRun>=kGridOffsetRunFromList&&(nRun<kGridMaxRunsFromList)){
1476            Printf("AnalysisTrainPWG4Jets Adding run number from File %s", Form(kGridRunPattern.Data(),iRun));
1477            plugin->AddRunNumber(Form(kGridRunPattern.Data(),iRun));
1478
1479          }
1480          else{
1481            Printf("AnalysisTrainPWG4Jets Skipping run number from File %d", iRun);
1482          }
1483          nRun++; 
1484        }
1485        else{
1486          Printf("AnalysisTrainPWG4Jets Skipping run number from File %d", iRun);
1487        }
1488      }
1489    }
1490
1491 // Method 2: Declare existing data files (raw collections, xml collections, root file)
1492 // If no path mentioned data is supposed to be in the work directory (see SetGridWorkingDir())
1493 // XML collections added via this method can be combined with the first method if
1494 // the content is compatible (using or not tags)
1495 //   plugin->AddDataFile("tag.xml");
1496 //   plugin->AddDataFile("/alice/data/2008/LHC08c/000057657/raw/Run57657.Merged.RAW.tag.root");
1497 // Define alien work directory where all files will be copied. Relative to alien $HOME.
1498    TString alien_workdir = "";
1499    
1500    if (iAODanalysis)  alien_workdir += "analysisAOD";
1501    else               alien_workdir += "analysisESD";    
1502    if(kGridDataSet.Length()>0)alien_workdir += Form("/%s",kGridDataSet.Data());
1503    plugin->SetGridWorkingDir(alien_workdir.Data());
1504
1505    // Declare alien output directory. Relative to working directory.
1506    if (!kGridOutdir.Length()) kGridOutdir = Form("output_%s",kTrainName.Data());
1507    plugin->SetGridOutputDir(kGridOutdir);
1508
1509    // Add external packages
1510    if (iJETAN||iDIJETAN) {
1511       plugin->AddExternalPackage("boost::v1_43_0");
1512       plugin->AddExternalPackage("cgal::v3.6");
1513       plugin->AddExternalPackage("fastjet::v2.4.2");
1514    }   
1515
1516
1517    // set extra libs before par file compilation
1518    anaLibs += kGridExtraFiles;
1519    anaLibs     = anaLibs.Strip();   
1520    Printf("anaLibs %s",anaLibs.Data());
1521    Printf("anaLibsExtra %s",anaLibsExtra.Data());
1522
1523    if (anaLibs.Length())          plugin->SetAdditionalLibs(anaLibs.Data());
1524    if (anaLibsExtra.Length())     plugin->SetAdditionalRootLibs(anaLibsExtra.Data());
1525
1526    TString ana_sources = "";
1527    TString ana_add = "";
1528    if (kUsePAR && anaPars.Length()) {
1529       printf("%s\n", anaPars.Data());
1530       TObjArray *arr;
1531       TObjString *objstr;
1532       arr = anaPars.Tokenize(" ");
1533       TIter next(arr);
1534       while ((objstr=(TObjString*)next())) plugin->EnablePackage(objstr->GetString());
1535       delete arr;
1536    } 
1537    
1538 // Declare the analysis source files names separated by blancs. To be compiled runtime
1539 // using ACLiC on the worker nodes.
1540    ana_sources = anaSources.Strip();
1541 // Declare all libraries (other than the default ones for the framework. These will be
1542 // loaded by the generated analysis macro. Add all extra files (task .cxx/.h) here.
1543
1544    if (ana_sources.Length()) plugin->SetAnalysisSource(ana_sources);
1545    plugin->SetExecutableCommand(kPluginExecutableCommand.Data());  
1546    // Declare the output file names separated by blancs.
1547    // (can be like: file.root or file.root@ALICE::Niham::File)
1548    plugin->SetMergeExcludes(kGridMergeExclude);
1549    plugin->SetMaxMergeFiles(kGridMaxMergeFiles);
1550    plugin->SetNrunsPerMaster(kGridRunsPerMaster);
1551    plugin->SetMergeViaJDL(kPluginMergeViaJDL);
1552    // Use fastread option
1553    plugin->SetFastReadOption(kPluginFastReadOption);
1554    // UseOverwrite mode
1555    plugin->SetOverwriteMode(kPluginOverwriteMode); 
1556    // Optionally define the files to be archived.
1557    //   plugin->SetOutputArchive("log_archive.zip:stdout,stderr@ALICE::NIHAM::File root_archive.zip:AliAOD.root,AOD.tag.root@ALICE::NIHAM::File");
1558    plugin->SetOutputToRunNo(kPluginOutputToRunNumber);     // write the output to subdirs named after run number
1559
1560    // Optionally set a name for the generated analysis macro (default MyAnalysis.C)
1561    plugin->SetAnalysisMacro(Form("%s.C", kTrainName.Data()));
1562    // Optionally set maximum number of input files/subjob (default 100, put 0 to ignore)
1563    plugin->SetSplitMaxInputFileNumber(kGridFilesPerJob);
1564    // Optionally set number of failed jobs that will trigger killing waiting sub-jobs.
1565    //   plugin->SetMaxInitFailed(5);
1566    // Optionally resubmit threshold.
1567    // plugin->SetMasterResubmitThreshold(90);
1568    // Optionally set time to live (default 30000 sec)
1569    plugin->SetTTL(54000); // 15h...
1570    // Optionally set input format (default xml-single)
1571    plugin->SetInputFormat("xml-single");
1572    // Optionally modify the name of the generated JDL (default analysis.jdl)
1573    plugin->SetJDLName(Form("%s.jdl", kTrainName.Data()));
1574    // Optionally modify the executable name (default analysis.sh)
1575    plugin->SetExecutable(Form("%s.sh", kTrainName.Data()));
1576    // Optionally modify job price (default 1)
1577    plugin->SetPrice(1);      
1578    // Optionally modify split mode (default 'se')    
1579    plugin->SetSplitMode("se");
1580    return plugin;
1581 }
1582 //______________________________________________________________________________
1583 Bool_t LoadConfig(const char *filename)
1584 {
1585 // Read train configuration from file
1586    if (gSystem->AccessPathName(filename)) {
1587       ::Error("AnalysisTrainPWG4Jets.C::LoadConfig", "Config file name not found");
1588       return kFALSE;
1589    }   
1590    gROOT->ProcessLine(Form(".x %s", filename));
1591    ::Info("AnalysisTrainPWG4Jets.C::LoadConfig", "Train configuration loaded from file %s", filename);
1592    return kTRUE;
1593 }