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