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